File tree Expand file tree Collapse file tree 5 files changed +83
-0
lines changed Expand file tree Collapse file tree 5 files changed +83
-0
lines changed Original file line number Diff line number Diff line change
1
+ import os
2
+
3
+ fn main () {
4
+ lines := os.read_lines ('map.input' )!
5
+
6
+ mut trailheads := [][2 ]int {}
7
+ for y, line in lines {
8
+ for x, c in line {
9
+ if c == `0` {
10
+ trailheads << [y, x]!
11
+ }
12
+ }
13
+ }
14
+
15
+ mut state := State{
16
+ lines: lines
17
+ }
18
+
19
+ mut total1 := 0
20
+ mut total2 := 0
21
+ for th in trailheads {
22
+ total1 + = state.traverse (th[0 ], th[1 ])
23
+ total2 + = state.part2 ()
24
+ }
25
+
26
+ println ('part1: ${total1} ' )
27
+ println ('part2: ${total2} ' )
28
+ }
29
+
30
+ struct State {
31
+ lines []string
32
+ mut :
33
+ trailends map [string ]int
34
+ }
35
+
36
+ fn (mut s State) traverse (y int , x int ) int {
37
+ s.trailends = map [string ]int {}
38
+ s.t (y, x, `0` )
39
+ return s.trailends.len
40
+ }
41
+
42
+ fn (s State) part2 () int {
43
+ mut total := 0
44
+ for _, v in s.trailends {
45
+ total + = v
46
+ }
47
+ return total
48
+ }
49
+
50
+ const offsets = [
51
+ [0 , 1 ]! ,
52
+ [1 , 0 ]! ,
53
+ [0 , - 1 ]! ,
54
+ [- 1 , 0 ]! ,
55
+ ]
56
+
57
+ fn (mut s State) t (y int , x int , current u8 ) {
58
+ for off in offsets {
59
+ ny := y + off[0 ]
60
+ nx := x + off[1 ]
61
+ if ny < 0 || ny > = s.lines.len || nx < 0 || nx > = s.lines[0 ].len {
62
+ continue
63
+ }
64
+ if s.lines[ny][nx] != current + 1 {
65
+ continue
66
+ }
67
+ if current == `8` {
68
+ s.trailends['${ny} ,${nx} ' ]++
69
+ continue
70
+ }
71
+ s.t (ny, nx, s.lines[ny][nx])
72
+ }
73
+ }
Original file line number Diff line number Diff line change
1
+ 89010123
2
+ 78121874
3
+ 87430965
4
+ 96549874
5
+ 45678903
6
+ 32019012
7
+ 01329801
8
+ 10456732
Original file line number Diff line number Diff line change
1
+ part1: 36
2
+ part2: 81
You can’t perform that action at this time.
0 commit comments