|
| 1 | +import extra |
| 2 | +import gleam/int |
| 3 | +import gleam/list |
| 4 | +import gleam/set.{type Set} |
| 5 | +import grid.{type Grid, type XY} |
| 6 | + |
| 7 | +pub fn parse(input: String) -> Grid(Int) { |
| 8 | + grid.from_string(input) |
| 9 | + |> grid.map(fn(_, c) { extra.yolo_int(c) }) |
| 10 | +} |
| 11 | + |
| 12 | +pub fn pt_1(input: Grid(Int)) { |
| 13 | + let starting_positions: List(XY) = grid.find_all_exact(input, 0) |
| 14 | + starting_positions |
| 15 | + |> list.map(trailheads_count(input, _)) |
| 16 | + |> int.sum |
| 17 | +} |
| 18 | + |
| 19 | +pub fn pt_2(input: Grid(Int)) { |
| 20 | + let starting_positions: List(XY) = grid.find_all_exact(input, 0) |
| 21 | + starting_positions |
| 22 | + |> list.map(trailheads_rating(input, _)) |
| 23 | + |> int.sum |
| 24 | +} |
| 25 | + |
| 26 | +type Trailhead { |
| 27 | + Trailhead(xy: XY, height: Int) |
| 28 | +} |
| 29 | + |
| 30 | +fn trailheads_count(input: Grid(Int), start: XY) -> Int { |
| 31 | + find_trailheads( |
| 32 | + input, |
| 33 | + todos: [Trailhead(xy: start, height: 0)], |
| 34 | + count: 0, |
| 35 | + seen: set.new(), |
| 36 | + ) |
| 37 | + |> fn(x) { set.size(x.1) } |
| 38 | +} |
| 39 | + |
| 40 | +fn trailheads_rating(input: Grid(Int), start: XY) -> Int { |
| 41 | + find_trailheads( |
| 42 | + input, |
| 43 | + todos: [Trailhead(xy: start, height: 0)], |
| 44 | + count: 0, |
| 45 | + seen: set.new(), |
| 46 | + ) |
| 47 | + |> fn(x) { x.0 } |
| 48 | +} |
| 49 | + |
| 50 | +fn find_trailheads( |
| 51 | + input: Grid(Int), |
| 52 | + todos todos: List(Trailhead), |
| 53 | + count count: Int, |
| 54 | + seen seen: Set(XY), |
| 55 | +) -> #(Int, Set(XY)) { |
| 56 | + case todos { |
| 57 | + [] -> #(count, seen) |
| 58 | + [todo_, ..rest] -> { |
| 59 | + case todo_.height == 9 { |
| 60 | + True -> |
| 61 | + find_trailheads( |
| 62 | + input, |
| 63 | + todos: rest, |
| 64 | + count: count + 1, |
| 65 | + seen: set.insert(seen, todo_.xy), |
| 66 | + ) |
| 67 | + False -> { |
| 68 | + let added_todos = |
| 69 | + grid.neighbours(input, todo_.xy, grid.orthogonal_dirs) |
| 70 | + |> list.filter(fn(neighbour) { neighbour.1 == Ok(todo_.height + 1) }) |
| 71 | + |> list.map(fn(neighbour) { |
| 72 | + Trailhead(xy: neighbour.0, height: todo_.height + 1) |
| 73 | + }) |
| 74 | + find_trailheads( |
| 75 | + input, |
| 76 | + todos: list.append(rest, added_todos), |
| 77 | + count: count, |
| 78 | + seen: seen, |
| 79 | + ) |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | +} |
0 commit comments