-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday02.go
86 lines (74 loc) · 1.89 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
82
83
84
85
86
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type Coordinates struct {
x, depth, aim int
}
// Read the input file.
func getInput() []string {
file, err := os.Open("2021/inputs/day02.txt")
if err != nil {
log.Fatalf("Failed to open file!")
}
defer file.Close()
scanner := bufio.NewScanner(file)
var returnSlice []string
for scanner.Scan() {
lineStr := scanner.Text()
returnSlice = append(returnSlice, lineStr)
}
return returnSlice
}
// Track horizontal position (x) and depth given a set of instructions
func partOne(inputVal []string) int {
coordinates := Coordinates{0, 0, 0}
var instruction []string
for i := 0; i < len(inputVal); i++ {
instruction = strings.Split(inputVal[i], " ")
magnitude, err := strconv.Atoi(instruction[1])
if err != nil {
log.Fatal(err)
}
if instruction[0] == "forward" {
coordinates.x += magnitude
} else if instruction[0] == "down" {
coordinates.depth += magnitude
} else if instruction[0] == "up" {
coordinates.depth -= magnitude
}
}
return coordinates.x * coordinates.depth
}
// Track horizontal position (x), depth, and aim given a set of instructions
func partTwo(inputVal []string) int {
coordinates := Coordinates{0, 0, 0}
var instruction []string
for i := 0; i < len(inputVal); i++ {
instruction = strings.Split(inputVal[i], " ")
magnitude, err := strconv.Atoi(instruction[1])
if err != nil {
log.Fatal(err)
}
if instruction[0] == "forward" {
coordinates.x += magnitude
coordinates.depth += coordinates.aim * magnitude
} else if instruction[0] == "down" {
coordinates.aim += magnitude
} else if instruction[0] == "up" {
coordinates.aim -= magnitude
}
}
return coordinates.x * coordinates.depth
}
// Run both parts
func main() {
inputVal := getInput()
fmt.Printf("Part One answer is: %d \n", partOne(inputVal))
fmt.Printf("Part Two answer is: %d \n", partTwo(inputVal))
}