day 2 part 2
This commit is contained in:
parent
c53304fa73
commit
4e35ec07be
2 changed files with 25 additions and 10 deletions
|
@ -2,6 +2,10 @@ defmodule AdventOfCode.Day02 do
|
|||
@moduledoc """
|
||||
Day 2
|
||||
"""
|
||||
|
||||
def parse_action("forward " <> v), do: {:forward, String.to_integer(v)}
|
||||
def parse_action("down " <> v), do: {:down, String.to_integer(v)}
|
||||
def parse_action("up " <> v), do: {:up, String.to_integer(v)}
|
||||
end
|
||||
|
||||
defmodule AdventOfCode.Day02.Part1 do
|
||||
|
@ -23,10 +27,6 @@ defmodule AdventOfCode.Day02.Part1 do
|
|||
|> product()
|
||||
end
|
||||
|
||||
defp parse_action("forward " <> v), do: {:forward, String.to_integer(v)}
|
||||
defp parse_action("down " <> v), do: {:down, String.to_integer(v)}
|
||||
defp parse_action("up " <> v), do: {:up, String.to_integer(v)}
|
||||
|
||||
defp apply_action({:forward, v}, {horiz, depth}), do: {horiz + v, depth}
|
||||
defp apply_action({:down, v}, {horiz, depth}), do: {horiz, depth + v}
|
||||
defp apply_action({:up, v}, {horiz, depth}), do: {horiz, depth - v}
|
||||
|
@ -45,8 +45,18 @@ defmodule AdventOfCode.Day02.Part2 do
|
|||
import AdventOfCode.Day02, warn: false
|
||||
|
||||
@impl PuzzleSolver
|
||||
def solve(_input_stream) do
|
||||
:ok |> to_string()
|
||||
def solve(input_stream) do
|
||||
input_stream
|
||||
|> Stream.map(&String.trim/1)
|
||||
|> Stream.map(&parse_action/1)
|
||||
|> Enum.reduce({0, 0, 0}, &apply_action/2)
|
||||
|> product()
|
||||
end
|
||||
|
||||
defp apply_action({:forward, v}, {horiz, depth, aim}), do: {horiz + v, depth + aim * v, aim}
|
||||
defp apply_action({:down, v}, {horiz, depth, aim}), do: {horiz, depth, aim + v}
|
||||
defp apply_action({:up, v}, {horiz, depth, aim}), do: {horiz, depth, aim - v}
|
||||
|
||||
defp product({x, y, _z}), do: x * y
|
||||
end
|
||||
|
||||
|
|
|
@ -1,11 +1,16 @@
|
|||
defmodule AdventOfCode.Day02.Part2Test do
|
||||
use AdventOfCode.PuzzleCase, module: AdventOfCode.Day02.Part2
|
||||
|
||||
test "returns :ok" do
|
||||
test "returns the product of horizontal position and depth" do
|
||||
input = ~S"""
|
||||
input
|
||||
forward 5
|
||||
down 5
|
||||
forward 8
|
||||
up 3
|
||||
down 8
|
||||
forward 2
|
||||
"""
|
||||
|
||||
assert_solution(input, "ok")
|
||||
assert_solution(input, 900)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue