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
|
import adglent.{First, Second}
import gleam/io
import gleam/string
import gleam/list
import gleam/order
import gleam/int
import gleam/iterator
import gleam/result
import utilities/memo.{type Cache}
fn parse(input) {
input
|> string.split("\n")
|> list.map(string.to_graphemes)
|> list.transpose()
}
fn roll_boulders(strs: List(String)) {
{
use chunks <- list.map(list.chunk(strs, fn(c) { c == "O" || c == "." }))
list.sort(chunks, order.reverse(string.compare))
}
|> list.flatten
}
fn score(matrix, cache) {
use <- memo.memoize(cache, matrix)
{
use col <- list.map(matrix)
list.index_map(list.reverse(col), fn(i, c) { #(i + 1, c) })
|> list.fold(
0,
fn(acc, tup) {
case tup {
#(n, "O") -> acc + n
_ -> acc
}
},
)
}
|> int.sum
}
pub fn part1(input: String) {
use cache: Cache(List(List(String)), Int) <- memo.create()
input
|> parse
|> list.map(roll_boulders)
|> score(cache)
|> string.inspect
}
fn rotate(matrix) {
matrix
|> list.map(list.reverse)
|> list.transpose
}
fn spin_the_board(matrix, cache) {
use <- memo.memoize(cache, matrix)
matrix
|> list.map(roll_boulders)
|> rotate
}
pub fn part2(input: String) {
use cache: Cache(List(List(String)), List(List(String))) <- memo.create()
use score_cache: Cache(List(List(String)), Int) <- memo.create()
input
|> parse
|> iterator.iterate(spin_the_board(_, cache))
|> iterator.map(score(_, score_cache))
|> iterator.at(10000)
|> string.inspect
}
pub fn main() {
let assert Ok(part) = adglent.get_part()
let assert Ok(input) = adglent.get_input("14")
case part {
First ->
part1(input)
|> adglent.inspect
|> io.println
Second ->
part2(input)
|> adglent.inspect
|> io.println
}
}
|