diff options
author | HJ <thechairman@thechairman.info> | 2021-12-09 18:05:04 -0500 |
---|---|---|
committer | HJ <thechairman@thechairman.info> | 2021-12-09 18:05:04 -0500 |
commit | 527bc4762f9c66c9244f0ac1fbee6357478ac9ef (patch) | |
tree | ecd3ffc97de5aab201699f93aab1e0417ac3d25d /2021/day-02 | |
download | gleam_aoc-527bc4762f9c66c9244f0ac1fbee6357478ac9ef.tar.gz gleam_aoc-527bc4762f9c66c9244f0ac1fbee6357478ac9ef.zip |
putting all my solutions together in 1 repository
Diffstat (limited to '2021/day-02')
-rw-r--r-- | 2021/day-02/day-02.ex | 32 | ||||
-rw-r--r-- | 2021/day-02/day-02.rkt | 39 |
2 files changed, 71 insertions, 0 deletions
diff --git a/2021/day-02/day-02.ex b/2021/day-02/day-02.ex new file mode 100644 index 0000000..d37ab05 --- /dev/null +++ b/2021/day-02/day-02.ex @@ -0,0 +1,32 @@ +defmodule Day02 do + def part_one(data) do + data + |> Enum.reduce(%{pos: 0, dep: 0}, &method_one/2) + |> get_answer() + end + + def part_two(data) do + data + |> Enum.reduce(%{pos: 0, dep: 0, aim: 0}, &method_two/2) + |> get_answer() + end + + defp method_one({:forward, x}, s), do: %{s | pos: s.pos + x} + defp method_one({:up, x}, s), do: %{s | dep: s.dep - x} + defp method_one({:down, x}, s), do: %{s | dep: s.dep + x} + + defp method_two({:forward, x}, s), do: %{s | pos: s.pos + x, dep: s.dep + s.aim * x} + defp method_two({:up, x}, s), do: %{s | aim: s.aim - x} + defp method_two({:down, x}, s), do: %{s | aim: s.aim + x} + + defp get_answer(s), do: s.pos * s.dep +end + +data = + File.read!("day-02/input.txt") + |> String.split("\n", trim: true) + |> Enum.map(&String.split/1) + |> Enum.map(fn [dir, amt] -> {String.to_atom(dir), String.to_integer(amt)} end) + +Day02.part_one(data) |> IO.inspect() +Day02.part_two(data) |> IO.inspect() diff --git a/2021/day-02/day-02.rkt b/2021/day-02/day-02.rkt new file mode 100644 index 0000000..dbd1275 --- /dev/null +++ b/2021/day-02/day-02.rkt @@ -0,0 +1,39 @@ +#lang racket +(require advent-of-code + threading + algorithms) + +(define motion-data + (~> (open-aoc-input (find-session) 2021 2 #:cache (string->path "./cache")) + (port->list read _) + (chunks-of _ 2))) + +;; part 1 +(for/fold ([depth 0] + [position 0] + #:result (* depth position)) + ([motion (in-list motion-data)]) + (match motion + [(list 'forward x) (values depth + (+ position x))] + [(list 'up x) (values (- depth x) + position)] + [(list 'down x) (values (+ depth x) + position)])) + +;; part 2 +(for/fold ([aim 0] + [depth 0] + [position 0] + #:result (* depth position)) + ([motion (in-list motion-data)]) + (match motion + [(list 'forward x) (values aim + (+ depth (* aim x)) + (+ position x))] + [(list 'up x) (values (- aim x) + depth + position)] + [(list 'down x) (values (+ aim x) + depth + position)]))
\ No newline at end of file |