-
Notifications
You must be signed in to change notification settings - Fork 0
/
dive.go
111 lines (90 loc) · 1.8 KB
/
dive.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
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) (product int) {
horiz := 0
depth := 0
for i := 0; i < len(spl); i += 2 {
dir := spl[i]
units := strToInt(spl[i+1])
if debug {
log.Println("dir =>", dir, ", units =>", units)
}
switch dir {
case "forward":
horiz += units
break
case "down":
depth += units
case "up":
depth -= units
default:
log.Panicln("Unknown dir =>", dir)
}
}
log.Println("Part1: horiz =>", horiz, ", depth => ", depth)
return horiz * depth
}
func part2(spl []string, debug bool) (product int) {
horiz := 0
depth := 0
aim := 0
for i := 0; i < len(spl); i += 2 {
dir := spl[i]
units := strToInt(spl[i+1])
if debug {
log.Println("dir =>", dir, ", units =>", units)
}
switch dir {
case "forward":
horiz += units
if debug {
log.Println("Fw with current aim =>", aim, " -> depth + ", aim*units)
}
depth += aim * units
break
case "down":
aim += units
case "up":
aim -= units
default:
log.Panicln("Unknown dir =>", dir)
}
}
log.Println("Part2: horiz =>", horiz, ", depth => ", depth)
return horiz * depth
}
func main() {
str := readFile(pathInput)
// fields --> split by whitespace and newline
splice := strings.Fields(str)
prod1 := part1(splice, false)
log.Println("Part1 result =>", prod1)
prod2 := part2(splice, true)
log.Println("Part2 result =>", prod2)
}