-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3.mar
70 lines (58 loc) · 2.02 KB
/
day3.mar
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
import ../stdlib.mar
fun is_digit(char: Char): Bool { {#0..=#9}.contains(char) }
fun is_symbol(char: Char): Bool { not(char.is_digit()) and char != #. }
fun main(): Never {
var grid = read_file("advent/day3.big").unwrap().to_string().into_grid()
var grid = uninitialized_slice[Slice[Char]](lines.len)
for it in lines.iter().enumerate() do grid.get_ref(it.index).* = it.item.chars()
println(grid.width())
println(grid.height())
var sum = 0
for y in 0..grid.height() do
for x in 0..grid.width() do {
var char = grid.get(x, y)
if char.is_digit() and not(grid.get(x - 1, y).is_digit())
then {
var end = x
loop if grid.get(end, y).is_digit() then end = end + 1 else break
var num = grid.get(y).subslice(x..end).parse_int()
var adjacent = list[Point[Int]]()
for xx in {x - 1}..=end do {
adjacent.&.push(Point { x = xx, y = y - 1 })
adjacent.&.push(Point { x = xx, y = y + 1 })
}
adjacent.&.push(Point { x = x - 1, y })
adjacent.&.push(Point { x = end, y })
var next_to_symbol = false
for pos in adjacent do
if grid.get(pos.x, pos.y).is_symbol() then next_to_symbol = true()
if next_to_symbol then {
print(num)
println(" is a part")
sum = sum.add(num)
} else {
print(num)
println(" is NOT a part")
}
}
}
println(sum)
exit(0)
}
fun into_grid(input: String): Grid {
var lines = input.lines()
var width = lines.get(0).len
var height = lines.len
var cells = uninitialized_matrix[Char](width @ lines.len)
for it in lines.iter().enumerate() do
cells.get_ref(it.index).* = it.item.chars()
Grid { cells }
}
struct Grid { cells: Matrix[Char] }
fun width(grid: Slice[Slice[Char]]): Int { grid.get(0).len }
fun height(grid: Slice[Slice[Char]]): Int { grid.len }
fun get(grid: Slice[Slice[Char]], x: Int, y: Int): Char {
if x < 0 or x >= grid.width() or y < 0 or y >= grid.height()
then return #.
grid.get(y).get(x)
}