From 663165a30d0ad23ad47497d8b6ffbf4c2c9b3c6b Mon Sep 17 00:00:00 2001 From: sloane <1699281+sloanelybutsurely@users.noreply.github.com> Date: Sun, 3 Dec 2023 10:25:43 -0500 Subject: [PATCH] solve 2023 3.2 --- 2023/elixir/lib/2023/3.ex | 37 ++++++++++++++++++++++++++++++++++++- README.md | 2 +- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/2023/elixir/lib/2023/3.ex b/2023/elixir/lib/2023/3.ex index 71314a6..0e15f78 100644 --- a/2023/elixir/lib/2023/3.ex +++ b/2023/elixir/lib/2023/3.ex @@ -31,7 +31,18 @@ aoc 2023, 3 do |> Enum.sum() end - def p2(_input) do + def p2(input) do + grid = + input + |> String.split("\n") + |> Enum.map(&String.to_charlist/1) + |> to_grid() + + for {coord, "*"} <- grid, is_gear(grid, coord), reduce: 0 do + sum -> + {_, [a, b]} = neighboring_numbers(grid, coord) + sum + a * b + end end def to_grid(lines) do @@ -90,4 +101,28 @@ aoc 2023, 3 do {y, x} end end + + def neighboring_numbers(grid, coord, already_seen \\ MapSet.new()) do + for c <- neighboring_coords(coord), reduce: {already_seen, []} do + {seen, numbers} -> + case Map.get(grid, c) do + {id, n} -> + if MapSet.member?(seen, id) do + {seen, numbers} + else + {MapSet.put(seen, id), [n | numbers]} + end + + _ -> + {seen, numbers} + end + end + end + + def is_gear(grid, coord) do + case neighboring_numbers(grid, coord) do + {_, [_, _]} -> true + _ -> false + end + end end diff --git a/README.md b/README.md index 55cf7c1..8a4b0de 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ 1. [2020] **17/50** 🌟 1. [2021] **43/50** 🌟 1. [2022] **14/50** 🌟 -1. [2023] **5/50** 🌟 +1. [2023] **6/50** 🌟 [2015]: ./2015 [2017]: ./2017