|
| 1 | +import gleam/dict |
| 2 | +import gleam/list |
| 3 | +import gleam/set |
| 4 | +import grid.{type Dims, type Grid, type XY} |
| 5 | + |
| 6 | +pub fn parse(input: String) -> Grid(String) { |
| 7 | + grid.from_string(input) |
| 8 | + |> grid.filter(fn(_, c) { c != "." }) |
| 9 | +} |
| 10 | + |
| 11 | +pub fn pt_1(input: Grid(String)) { |
| 12 | + input |
| 13 | + |> grid.to_list |
| 14 | + |> list.group(by: fn(cell) { cell.1 }) |
| 15 | + |> dict.values |
| 16 | + |> list.map(fn(nodes) { list.map(nodes, fn(node) { node.0 }) }) |
| 17 | + |> list.fold(from: set.new(), with: fn(acc, nodes) { |
| 18 | + nodes |
| 19 | + |> list.combination_pairs |
| 20 | + |> list.flat_map(antinodes_xy_pt1) |
| 21 | + |> list.filter(fn(xy) { grid.in_grid(input, xy) }) |
| 22 | + |> set.from_list |
| 23 | + |> set.union(acc) |
| 24 | + }) |
| 25 | + |> set.size |
| 26 | +} |
| 27 | + |
| 28 | +fn antinodes_xy_pt1(pair: #(XY, XY)) -> List(XY) { |
| 29 | + let #(a, b) = pair |
| 30 | + let diff = grid.xy_sub(a, b) |
| 31 | + [grid.xy_add(a, diff), grid.xy_sub(b, diff)] |
| 32 | +} |
| 33 | + |
| 34 | +pub fn pt_2(input: Grid(String)) { |
| 35 | + input |
| 36 | + |> grid.to_list |
| 37 | + |> list.group(by: fn(cell) { cell.1 }) |
| 38 | + |> dict.values |
| 39 | + |> list.map(fn(nodes) { list.map(nodes, fn(node) { node.0 }) }) |
| 40 | + |> list.fold(from: set.new(), with: fn(acc, nodes) { |
| 41 | + nodes |
| 42 | + |> list.combination_pairs |
| 43 | + |> list.flat_map(antinodes_xy_pt2(input.dims, _)) |
| 44 | + |> set.from_list |
| 45 | + |> set.union(acc) |
| 46 | + }) |
| 47 | + |> set.size |
| 48 | +} |
| 49 | + |
| 50 | +fn antinodes_xy_pt2(dims: Dims, pair: #(XY, XY)) -> List(XY) { |
| 51 | + let #(a, b) = pair |
| 52 | + list.append( |
| 53 | + cast_ray(dims, a, grid.xy_sub(a, b), [a]), |
| 54 | + cast_ray(dims, b, grid.xy_sub(b, a), [b]), |
| 55 | + ) |
| 56 | +} |
| 57 | + |
| 58 | +/// Also return the start point |
| 59 | +fn cast_ray(dims: Dims, start: XY, d: XY, acc: List(XY)) -> List(XY) { |
| 60 | + let next = grid.xy_add(start, d) |
| 61 | + case grid.in_dims(dims, next) { |
| 62 | + False -> acc |
| 63 | + True -> cast_ray(dims, next, d, [next, ..acc]) |
| 64 | + } |
| 65 | +} |
0 commit comments