Repository navigation
Expand file tree
/
Copy pathday04.kk
More file actions
93 lines (81 loc) · 2.09 KB
/
Copy pathday04.kk
File metadata and controls
93 lines (81 loc) · 2.09 KB
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
import util/prelude
type cell
Roll
Empty
alias grid = (vector<vector<cell>>, int, int)
fun cell/show(c: cell)
match c
Roll -> "@"
Empty -> "."
fun grid/show(grid: grid)
try(fn ()
val (floor, rows, cols) = grid
var res := ""
list(0, rows - 1).foreach fn (i)
list(0, cols - 1).foreach fn (j)
res := res ++ floor[i][j].show
res := res ++ "\n"
res
, show)
fun parse-input()
val floor = get-input().slice.parse
many
val row = many
match one-of(".@")
'.' -> Empty
'@' -> Roll
new-line()
row.vector
.maybe.unjust.vector
val rows = floor.length
val cols = floor[0].length
(floor, rows, cols)
fun has-roll((floor, rows, cols): grid, i: int, j: int)
if i < 0 || j < 0 || i >= rows || j >= cols then
return False
match floor[i][j]
Roll -> True
Empty -> False
val neighbors = [
(-1, -1), (-1, 0), (-1, 1),
( 0, -1), ( 0, 1),
( 1, -1), ( 1, 0), ( 1, 1)
]
fun remove-rolls(grid: grid)
val (_, rows, cols) = grid
var res := 0
var new-floor: list<vector<cell>> := []
var new-row: list<cell> := []
list(0, rows - 1).foreach fn (i)
new-row := []
list(0, cols - 1).foreach fn (j)
if has-roll(grid, i, j) then
val rolls-around = neighbors.foldl(0, fn (curr, (di, dj)) curr + (if has-roll(grid, i + di, j + dj) then 1 else 0))
if rolls-around < 4 then
new-row := Cons(Empty, new-row)
res := res + 1
else
new-row := Cons(Roll, new-row)
else
new-row := Cons(Empty, new-row)
new-floor := Cons(new-row.reverse.vector, new-floor)
(res, new-floor.reverse.vector)
pub fun part-one()
parse-input().remove-rolls().fst
pub fun part-two()
val (floor-, rows, cols) = parse-input()
var floor := floor-
var res := 0
with here <- early-exit
while { True }
val (removed, next-floor) = remove-rolls((floor, rows, cols))
res := res + removed
floor := next-floor
if removed == 0 then
here.exit(res)
res
pub fun main()
with day(4)
// with example-input
// part-one()
part-two()