From 4e35ec07bea705cefdf7a29bb10758a753adcbfe Mon Sep 17 00:00:00 2001 From: Sloane Perrault Date: Wed, 21 Sep 2022 09:19:53 -0400 Subject: [PATCH] day 2 part 2 --- 2021/lib/advent_of_code/day02.ex | 22 ++++++++++++++----- .../test/advent_of_code/day02/part_2_test.exs | 13 +++++++---- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/2021/lib/advent_of_code/day02.ex b/2021/lib/advent_of_code/day02.ex index e263209..42e2c19 100644 --- a/2021/lib/advent_of_code/day02.ex +++ b/2021/lib/advent_of_code/day02.ex @@ -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 diff --git a/2021/test/advent_of_code/day02/part_2_test.exs b/2021/test/advent_of_code/day02/part_2_test.exs index 3095e6e..e6f91d6 100644 --- a/2021/test/advent_of_code/day02/part_2_test.exs +++ b/2021/test/advent_of_code/day02/part_2_test.exs @@ -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 \ No newline at end of file +end