diff --git a/2024/day8.exs b/2024/day8.exs index 694fc13..32b7f91 100755 --- a/2024/day8.exs +++ b/2024/day8.exs @@ -2,22 +2,19 @@ defmodule Day8 do def part1({x, y, frequencies}) do Enum.reduce(frequencies, MapSet.new(), fn antennas, antinodes -> - MapSet.union(antinodes, find_antinodes(antennas, x, y)) + antennas + |> find_pairs() + |> Enum.flat_map(fn pair -> find_antinodes(pair, x, y) end) + |> MapSet.new() + |> MapSet.union(antinodes) end) |> MapSet.size() end - def find_antinodes(antennas, x, y) do - antennas - |> find_pairs() - |> Enum.flat_map(fn pair -> calc_antinodes(pair, x, y) end) - |> MapSet.new() - end - def find_pairs([_]), do: [] def find_pairs([a | rest]), do: for(b <- rest, do: {a, b}) ++ find_pairs(rest) - def calc_antinodes({{x_a, y_a}, {x_b, y_b}}, max_x, max_y) do + def find_antinodes({{x_a, y_a}, {x_b, y_b}}, max_x, max_y) do dx = x_a - x_b dy = y_a - y_b antinode_1 = {x_a + dx, y_a + dy} @@ -30,19 +27,16 @@ defmodule Day8 do def part2({x, y, frequencies}) do Enum.reduce(frequencies, MapSet.new(), fn antennas, antinodes -> - MapSet.union(antinodes, find_resonant_harmonics(antennas, x, y)) + antennas + |> find_pairs() + |> Enum.flat_map(fn pair -> find_resonant_harmonics(pair, x, y) end) + |> MapSet.new() + |> MapSet.union(antinodes) end) |> MapSet.size() end - def find_resonant_harmonics(antennas, x, y) do - antennas - |> find_pairs - |> Enum.flat_map(fn pair -> calc_resonant_harmonics(pair, x, y) end) - |> MapSet.new() - end - - def calc_resonant_harmonics({{x_a, y_a}, {x_b, y_b}}, max_x, max_y) do + def find_resonant_harmonics({{x_a, y_a}, {x_b, y_b}}, max_x, max_y) do dx = x_a - x_b dy = y_a - y_b