-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
131 lines (109 loc) · 2.52 KB
/
main.go
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
package main
import (
"io"
"sort"
aoc "github.com/teivah/advent-of-code"
)
func fs1(input io.Reader) int {
lines := aoc.ReaderToStrings(input)
grid := make(map[aoc.Position]int)
for row, line := range lines {
for col := 0; col < len(line); col++ {
grid[aoc.Position{row, col}] = aoc.RuneToInt(rune(line[col]))
}
}
sum := 0
for pos, h := range grid {
n := getNeighbors(grid, pos)
if allAbove(h, n) {
sum += 1 + h
}
}
return sum
}
func allAbove(h int, neighbors []int) bool {
for _, neighbor := range neighbors {
if neighbor <= h {
return false
}
}
return true
}
func getNeighbors(grid map[aoc.Position]int, pos aoc.Position) []int {
var res []int
if v, exists := grid[pos.Delta(-1, 0)]; exists {
res = append(res, v)
}
if v, exists := grid[pos.Delta(1, 0)]; exists {
res = append(res, v)
}
if v, exists := grid[pos.Delta(0, -1)]; exists {
res = append(res, v)
}
if v, exists := grid[pos.Delta(0, 1)]; exists {
res = append(res, v)
}
return res
}
func getNeighborPositions(grid map[aoc.Position]int, pos aoc.Position) []aoc.Position {
var res []aoc.Position
p := pos.Delta(-1, 0)
if _, exists := grid[p]; exists {
res = append(res, p)
}
p = pos.Delta(1, 0)
if _, exists := grid[p]; exists {
res = append(res, p)
}
p = pos.Delta(0, -1)
if _, exists := grid[p]; exists {
res = append(res, p)
}
p = pos.Delta(0, 1)
if _, exists := grid[p]; exists {
res = append(res, p)
}
return res
}
func fs2(input io.Reader) int {
lines := aoc.ReaderToStrings(input)
grid := make(map[aoc.Position]int)
for row, line := range lines {
for col := 0; col < len(line); col++ {
grid[aoc.Position{row, col}] = aoc.RuneToInt(rune(line[col]))
}
}
lowPoints := findLowPoints(grid)
var res []int
for _, lowPoint := range lowPoints {
v := findLargest(grid, lowPoint, make(map[aoc.Position]bool))
res = append(res, v)
}
sort.Ints(res)
return res[len(res)-1] * res[len(res)-2] * res[len(res)-3]
}
func findLargest(grid map[aoc.Position]int, pos aoc.Position, visited map[aoc.Position]bool) int {
if visited[pos] || grid[pos] == 9 {
return 0
}
visited[pos] = true
neighbors := getNeighborPositions(grid, pos)
sum := 0
for _, neighbor := range neighbors {
if grid[neighbor] > grid[pos] {
v := findLargest(grid, neighbor, visited)
sum += v
}
}
return 1 + sum
}
func findLowPoints(grid map[aoc.Position]int) []aoc.Position {
var res []aoc.Position
for pos, h := range grid {
n := getNeighbors(grid, pos)
if allAbove(h, n) {
res = append(res, pos)
}
}
return res
}