|
| 1 | +defmodule AdventOfCode.Y2024.Day08 do |
| 2 | + @moduledoc """ |
| 3 | + --- Day 8: Resonant Collinearity --- |
| 4 | + Problem Link: https://adventofcode.com/2024/day/8 |
| 5 | + Difficulty: s |
| 6 | + Tags: grid enumeration coordinate-geometry |
| 7 | + """ |
| 8 | + alias AdventOfCode.Helpers.{InputReader, Transformers} |
| 9 | + |
| 10 | + def input, do: InputReader.read_from_file(2024, 8) |
| 11 | + |
| 12 | + def run(input \\ input()) do |
| 13 | + {width, height, antennas} = parse(input) |
| 14 | + |
| 15 | + p1 = solve(width, height, antennas, :part1) |
| 16 | + p2 = solve(width, height, antennas, :part2) |
| 17 | + |
| 18 | + {p1, p2} |
| 19 | + end |
| 20 | + |
| 21 | + defp solve(width, height, antennas, part) do |
| 22 | + for {_freq, coords} <- antennas, |
| 23 | + a1 <- coords, |
| 24 | + a2 <- coords, |
| 25 | + a1 != a2, |
| 26 | + reduce: MapSet.new() do |
| 27 | + acc -> |
| 28 | + generate_antinodes(a1, a2, width, height, part) |
| 29 | + |> Enum.reduce(acc, &MapSet.put(&2, &1)) |
| 30 | + end |
| 31 | + |> MapSet.size() |
| 32 | + end |
| 33 | + |
| 34 | + defp generate_antinodes({x1, y1}, {x2, y2}, w, h, :part1) do |
| 35 | + dx = x2 - x1 |
| 36 | + dy = y2 - y1 |
| 37 | + |
| 38 | + [{x1 - dx, y1 - dy}, {x2 + dx, y2 + dy}] |
| 39 | + |> Enum.filter(&in_bounds?(&1, w, h)) |
| 40 | + end |
| 41 | + |
| 42 | + defp generate_antinodes({x1, y1}, {x2, y2}, w, h, :part2) do |
| 43 | + dx = x2 - x1 |
| 44 | + dy = y2 - y1 |
| 45 | + g = Integer.gcd(abs(dx), abs(dy)) |
| 46 | + step_x = div(dx, g) |
| 47 | + step_y = div(dy, g) |
| 48 | + |
| 49 | + collect_line({x1, y1}, {step_x, step_y}, w, h) ++ |
| 50 | + collect_line({x1, y1}, {-step_x, -step_y}, w, h) |
| 51 | + end |
| 52 | + |
| 53 | + defp collect_line({x, y}, {dx, dy}, w, h) do |
| 54 | + if in_bounds?({x, y}, w, h) do |
| 55 | + [{x, y} | collect_line({x + dx, y + dy}, {dx, dy}, w, h)] |
| 56 | + else |
| 57 | + [] |
| 58 | + end |
| 59 | + end |
| 60 | + |
| 61 | + defp in_bounds?({x, y}, w, h), do: x >= 0 and x < w and y >= 0 and y < h |
| 62 | + |
| 63 | + def parse(data \\ input()) do |
| 64 | + lines = Transformers.lines(data) |
| 65 | + height = length(lines) |
| 66 | + width = lines |> List.first() |> String.length() |
| 67 | + |
| 68 | + antennas = |
| 69 | + lines |
| 70 | + |> Enum.with_index() |
| 71 | + |> Enum.reduce(%{}, fn {line, y}, acc -> |
| 72 | + line |
| 73 | + |> String.graphemes() |
| 74 | + |> Enum.with_index() |
| 75 | + |> Enum.reduce(acc, fn |
| 76 | + {".", _}, acc -> acc |
| 77 | + {char, x}, acc -> |
| 78 | + Map.update(acc, char, [{x, y}], &[{x, y} | &1]) |
| 79 | + end) |
| 80 | + end) |
| 81 | + |
| 82 | + {width, height, antennas} |
| 83 | + end |
| 84 | +end |
0 commit comments