-
Notifications
You must be signed in to change notification settings - Fork 0
/
day02.go
81 lines (70 loc) · 1.62 KB
/
day02.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
package main
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/dergeberl/aoc/utils"
)
type command struct {
direction string
step int
}
func main() {
input, err := os.ReadFile("input.txt")
if err != nil {
os.Exit(1)
}
fmt.Printf("Part 1: %v\n", SolveDay02Part1(string(input)))
fmt.Printf("Part 2: %v\n", SolveDay02Part2(string(input)))
}
// SolveDay02Part1 returns the depth multiplied by the horizontal position of the submarine, after following the steps
func SolveDay02Part1(input string) int {
c := convertInputInCommands(input)
var horizontal, depth int
for i := range c {
switch c[i].direction {
case "forward":
horizontal += c[i].step
case "down":
depth += c[i].step
case "up":
depth -= c[i].step
}
}
return horizontal * depth
}
// SolveDay02Part2 returns the depth multiplied by the horizontal position of the submarine,
// after following the steps with no direct up and down use an aim instead
func SolveDay02Part2(input string) int {
c := convertInputInCommands(input)
var aim, horizontal, depth int
for i := range c {
switch c[i].direction {
case "forward":
horizontal += c[i].step
depth += c[i].step * aim
case "down":
aim += c[i].step
case "up":
aim -= c[i].step
}
}
return horizontal * depth
}
func convertInputInCommands(input string) []command {
lines, _ := utils.InputToSlice(input)
c := make([]command, len(lines))
for i := range lines {
line := strings.Split(lines[i], " ")
if len(line) != 2 {
panic("do not end here")
}
stepInt, _ := strconv.Atoi(line[1])
c[i] = command{
direction: line[0],
step: stepInt,
}
}
return c
}