Advent of Code 2021 - Day 2
Utils
defmodule Utils do
def read_textarea(name) do
Stream.iterate("", fn _ -> IO.gets(name) end)
|> Stream.take_while(&(&1 != :eof))
|> Enum.join("\r\n")
end
end
{:module, Utils, <<70, 79, 82, 49, 0, 0, 7, ...>>, {:read_textarea, 1}}
Part 1
defmodule Day2 do
def solve(input) do
input
|> String.split(~r{\s}, trim: true)
|> Enum.chunk_every(2, 2)
|> Enum.map(fn [action, amount] -> {action, String.to_integer(amount)} end)
|> Enum.reduce(%{depth: 0, position: 0}, &move/2)
|> then(fn submarine -> submarine.depth * submarine.position end)
end
defp move({"forward", amount}, submarine) do
%{submarine | position: submarine.position + amount}
end
defp move({"down", amount}, submarine) do
%{submarine | depth: submarine.depth + amount}
end
defp move({"up", amount}, submarine) do
%{submarine | depth: submarine.depth - amount}
end
end
Day2.solve(Utils.read_textarea("example_input"))
Day2.solve(Utils.read_textarea("my_input"))
2039256
Part2
defmodule Day2.Part2 do
def solve(input) do
input
|> String.split(~r{\s}, trim: true)
|> Enum.chunk_every(2, 2)
|> Enum.map(fn [action, amount] -> {action, String.to_integer(amount)} end)
|> Enum.reduce(%{aim: 0, depth: 0, position: 0}, &move/2)
|> then(fn submarine -> submarine.depth * submarine.position end)
end
defp move({"forward", amount}, submarine) do
new_position = submarine.position + amount
new_depth = submarine.depth + submarine.aim * amount
%{submarine | position: new_position, depth: new_depth}
end
defp move({"down", amount}, submarine) do
%{submarine | aim: submarine.aim + amount}
end
defp move({"up", amount}, submarine) do
%{submarine | aim: submarine.aim - amount}
end
end
Day2.Part2.solve(Utils.read_textarea("example_input"))
Day2.Part2.solve(Utils.read_textarea("my_input"))
1856459736