-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
109 lines (85 loc) · 1.71 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
package main
import (
"bufio"
"fmt"
"io"
"os"
"path"
"strings"
)
func input() *os.File {
input, err := os.Open(path.Join("2021", "9", "input.txt"))
if err != nil {
panic(err)
}
return input
}
func parse(r io.Reader) [][]int {
scanner := bufio.NewScanner(r)
var cave [][]int
for scanner.Scan() {
line := scanner.Text()
var row []int
for _, rawHeight := range line {
row = append(row, int(rawHeight-48))
}
cave = append(cave, row)
}
if scanner.Err() != nil {
panic(scanner.Err())
}
return cave
}
func solve(r io.Reader) {
cave := parse(r)
totalRisk := 0
for _, lowPoint := range findLowPoints(cave) {
totalRisk += lowPoint + 1
}
fmt.Println(totalRisk)
}
func findLowPoints(cave [][]int) []int {
var lowPoints []int
for i := 0; i < len(cave); i++ {
for j := 0; j < len(cave[i]); j++ {
height := cave[i][j]
if smaller(height, adjacent(cave, i, j)) {
lowPoints = append(lowPoints, height)
}
}
}
return lowPoints
}
func smaller(value int, values []int) bool {
for _, otherValue := range values {
if value >= otherValue {
return false
}
}
return true
}
func adjacent(cave [][]int, i, j int) []int {
var adjacentHeights []int
for _, offset := range []struct{ i, j int }{
{i: 1, j: 0},
{i: 0, j: 1},
{i: -1, j: 0},
{i: 0, j: -1},
} {
height, ok := get(cave, i+offset.i, j+offset.j)
if ok {
adjacentHeights = append(adjacentHeights, height)
}
}
return adjacentHeights
}
func get(cave [][]int, i, j int) (int, bool) {
if i < 0 || j < 0 || i > len(cave)-1 || j > len(cave[0])-1 {
return 0, false
}
return cave[i][j], true
}
func main() {
solve(strings.NewReader("2199943210\n3987894921\n9856789892\n8767896789\n9899965678"))
solve(input())
}