From 1e974c56aeb8a0b0c8c596869a9a823d876e3481 Mon Sep 17 00:00:00 2001 From: Adam Millerchip Date: Mon, 9 Dec 2024 09:23:48 +0900 Subject: [PATCH] Simplify a bit by inlining a function --- 2024/day8.exs | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) 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