defmodule Load do
def input do
File.read!("inputs/day02.txt")
|> String.split("\n", trim: true)
|> Enum.map(fn line ->
[direction, value] = String.split(line)
[direction, String.to_integer(value)]
end)
end
end
Calculate the horizontal position and depth you would have after following the planned course.
Your horizontal position and depth both start at 0.
- forward X increases the horizontal position by X units.
- down X increases the depth by X units.
- up X decreases the depth by X units.
And multiply your final horizontal position by your final depth.
defmodule Part1 do
def final_position() do
input = Load.input()
final_position =
Enum.reduce(input, %{horizontal: 0, depth: 0}, fn [direction, value], position ->
case direction do
"forward" -> Map.update!(position, :horizontal, &(&1 + value))
"down" -> Map.update!(position, :depth, &(&1 + value))
"up" -> Map.update!(position, :depth, &(&1 - value))
end
end)
final_position.horizontal * final_position.depth
end
end
Part1.final_position()
As usual, you discover that the process is actually more complicated and the commands mean something entirely different
You'll also need to track a third value, aim, which also starts at 0.
- down X increases your aim by X units.
- up X decreases your aim by X units.
- forward X:
- increases your horizontal position by X units.
- increases your depth by your aim multiplied by X.
defmodule Part2 do
def final_position() do
input = Load.input()
final_position =
Enum.reduce(input, %{horizontal: 0, depth: 0, aim: 0}, fn [direction, value], position ->
case direction do
"forward" ->
position
|> Map.update!(:horizontal, &(&1 + value))
|> Map.update!(:depth, &(&1 + position.aim * value))
"down" ->
Map.update!(position, :aim, &(&1 + value))
"up" ->
Map.update!(position, :aim, &(&1 - value))
end
end)
final_position.horizontal * final_position.depth
end
end
Part2.final_position()
ExUnit.start(autorun: false)
defmodule Test do
use ExUnit.Case, async: true
test "part1" do
assert Part1.final_position() == 1_762_050
end
test "part2" do
assert Part2.final_position() == 1_855_892_637
end
end
ExUnit.run()