-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsonar_sweep.go
104 lines (82 loc) · 1.71 KB
/
sonar_sweep.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
package main
import (
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
const pathInput = "input.txt"
const pathTestInput = "test.txt"
func logErr(e error) {
if e != nil {
log.Panicln(e)
}
}
func strToInt(str string) (num int) {
num, err := strconv.Atoi(str)
logErr(err)
return num
}
func readFile(path string) (str string) {
fp, err := filepath.Abs(path)
logErr(err)
dat, err := os.ReadFile(fp)
logErr(err)
str = string(dat)
return str
}
func part1(spl []string, debug bool) (increases int) {
increases = 0
prev := -1
for _, line := range spl {
num := strToInt(line)
if prev < num && prev != -1 {
increases++
} else {
if debug {
log.Println("No increase =>", prev, num)
}
}
prev = num
}
return increases
}
func getSumOfLast3(spl []string, start int, debug bool) (sum int) {
if debug {
log.Println("get sum of", start, start+1, start+2)
}
sum = 0
sum += strToInt(spl[start])
sum += strToInt(spl[start+1])
sum += strToInt(spl[start+2])
return sum
}
func part2(spl []string, debug bool) (increases int) {
increases = 0
// start at 3 because we want to compare spl[0, 1, 2] and spl[1, 2, 3]
for i := 3; i < len(spl); i++ {
if debug {
log.Println(i, "======")
}
prev := getSumOfLast3(spl, i-3, debug)
curr := getSumOfLast3(spl, i-2, debug)
if prev < curr {
increases++
} else {
if debug {
log.Println("No increase =>", prev, curr, i)
}
}
}
return increases
}
func main() {
str := readFile(pathInput)
// fields --> split by whitespace and newline
splice := strings.Fields(str)
part1Res := part1(splice, false)
log.Println("Part1: increases =>", part1Res)
part2Res := part2(splice, false)
log.Println("Part2: increases =>", part2Res)
}