aboutsummaryrefslogtreecommitdiff
path: root/aoc2023-gleam/src/day3/solve.gleam
blob: ad975aad0111e61ee6bd0e6fa6f1717bc3b34ce9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import adglent.{First, Second}
import gleam/io
import gleam/dict.{type Dict}
import gleam/string
import gleam/list
import gleam/int
import gleam/order.{type Order, Eq}

type Coord {
  Coord(x: Int, y: Int)
}

type SymbolKind {
  Gear
  SomethingElse
}

type Symbol {
  Number(Int)
  Symbol(SymbolKind)
  Empty
}

type Board =
  Dict(Coord, Symbol)

type Cell {
  Cell(coord: Coord, symbol: Symbol)
}

type Part {
  Part(coords: List(Coord), part_number: Int)
}

fn to_symbol(c: String) -> Symbol {
  case int.parse(c), c {
    Ok(n), _ -> Number(n)
    _, "." -> Empty
    _, "*" -> Symbol(Gear)
    _, _ -> Symbol(SomethingElse)
  }
}

fn to_board(input: String) -> Board {
  {
    use y, r <- list.index_map(string.split(input, "\n"))
    use x, c <- list.index_map(string.to_graphemes(r))
    #(Coord(x, y), to_symbol(c))
  }
  |> list.flatten()
  |> dict.from_list()
}

fn cell_compare(a: Cell, b: Cell) -> Order {
  case int.compare(a.coord.y, b.coord.y) {
    Eq -> int.compare(a.coord.x, b.coord.x)
    other -> other
  }
}

fn find_all_part_digits(b: Board) -> List(Cell) {
  b
  |> dict.filter(fn(_, v) {
    case v {
      Number(_) -> True
      _ -> False
    }
  })
  |> dict.to_list()
  |> list.map(fn(tup) { Cell(tup.0, tup.1) })
  |> list.sort(cell_compare)
}

fn to_parts(cells: List(Cell)) -> List(Part) {
  do_parts(cells, [])
}

fn do_parts(cells: List(Cell), parts: List(Part)) -> List(Part) {
  case cells {
    [] -> parts
    [Cell(next, Number(n)), ..t] -> {
      case parts {
        [] -> do_parts(t, [Part([next], n), ..parts])
        [Part([prev, ..] as coords, n0), ..rest_parts] ->
          case { next.x - prev.x }, { next.y - prev.y } {
            1, 0 ->
              do_parts(t, [Part([next, ..coords], n0 * 10 + n), ..rest_parts])
            _, _ -> do_parts(t, [Part([next], n), ..parts])
          }
        _ -> panic
      }
    }
    _ -> panic
  }
}

fn all_neighbors(c: Coord) -> List(Coord) {
  use dx <- list.flat_map([-1, 0, 1])
  use dy <- list.filter_map([-1, 0, 1])
  case dx, dy {
    0, 0 -> Error(Nil)
    _, _ -> Ok(Coord(c.x + dx, c.y + dy))
  }
}

fn sum_valid_parts(acc: Int, part: Part, board: Board) -> Int {
  let neighbors =
    part.coords
    |> list.flat_map(all_neighbors)
    |> list.unique()

  let sym = [Ok(Symbol(Gear)), Ok(Symbol(SomethingElse))]
  case list.any(neighbors, fn(c) { list.contains(sym, dict.get(board, c)) }) {
    True -> acc + part.part_number
    False -> acc
  }
}

pub fn part1(input: String) -> Int {
  let board = to_board(input)

  board
  |> find_all_part_digits
  |> to_parts
  |> list.fold(0, fn(acc, p) { sum_valid_parts(acc, p, board) })
}

fn to_part_with_neighbors(part: Part) -> Part {
  part.coords
  |> list.flat_map(all_neighbors)
  |> list.unique
  |> Part(part.part_number)
}

fn find_part_numbers_near_gear(gear: Coord, parts: List(Part)) -> List(Int) {
  use part <- list.filter_map(parts)
  case list.contains(part.coords, gear) {
    True -> Ok(part.part_number)
    False -> Error(Nil)
  }
}

fn to_sum_of_gear_ratios(adjacent_parts: List(List(Int))) -> Int {
  use acc, ps <- list.fold(adjacent_parts, 0)
  case ps {
    [p1, p2] -> acc + p1 * p2
    _ -> acc
  }
}

pub fn part2(input: String) -> Int {
  let board = to_board(input)

  let parts =
    board
    |> find_all_part_digits
    |> to_parts
    |> list.map(to_part_with_neighbors)

  board
  |> dict.filter(fn(_, v) { v == Symbol(Gear) })
  |> dict.keys
  |> list.map(find_part_numbers_near_gear(_, parts))
  |> to_sum_of_gear_ratios
}

pub fn main() {
  let assert Ok(part) = adglent.get_part()
  let assert Ok(input) = adglent.get_input("3")
  case part {
    First ->
      part1(input)
      |> adglent.inspect
      |> io.println
    Second ->
      part2(input)
      |> adglent.inspect
      |> io.println
  }
}