-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday03.go
96 lines (82 loc) · 1.96 KB
/
day03.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
package main
import (
"fmt"
"io/ioutil"
"log"
"path/filepath"
"strings"
)
type Coordinates struct {
x, y int
}
// Read the input file.
func getInput() []string {
filepath, err := filepath.Abs("2020/inputs/day03.txt")
if err != nil {
log.Fatal(err)
}
inputVal, err := ioutil.ReadFile(filepath)
if err != nil {
log.Fatal(err)
}
return strings.Split(string(inputVal), "\n")
}
// Traverse the input at a slope of 3 right, 1 down and
// count the number of "trees"
func partOne(inputVal []string) int {
position := Coordinates{0, 0}
mapWidth := len(inputVal[0])
nTrees := 0
slope := []int{3, 1}
for i, element := range inputVal {
position.x = slope[0] * i
position.y = slope[1] * i
offset := (position.x / mapWidth) * mapWidth
adjustedPosition := Coordinates{position.x - offset, position.y}
if string(element[adjustedPosition.x]) == "#" {
nTrees++
}
}
return nTrees
}
// Traverse the input for a variety of slopes and multiple the results.
func partTwo(inputVal []string) int {
position := Coordinates{0, 0}
mapWidth := len(inputVal[0])
var results []int
slopes := [][]int{
{1, 1},
{3, 1},
{5, 1},
{7, 1},
{1, 2},
}
for _, slope := range slopes {
nTrees := 0
for i := 0; i < len(inputVal); i += slope[1] {
element := inputVal[i]
position.x = slope[0] * i
position.y = slope[1] * i
offset := (position.x / mapWidth) * mapWidth
adjustedPosition := Coordinates{position.x - offset, position.y}
fmt.Println(i, offset, position, adjustedPosition)
if string(element[adjustedPosition.x]) == "#" {
nTrees++
}
}
results = append(results, nTrees)
}
// Multiply the results together
answer := 1
for _, result := range results {
answer *= result
}
return answer
}
func main() {
inputVal := getInput()
partOneAnswer := partOne(inputVal)
partTwoAnswer := partTwo(inputVal)
fmt.Printf("PartOne - Number of Trees: %d\n", partOneAnswer)
fmt.Printf("PartTwo - Number of Trees Multiplied: %d", partTwoAnswer)
}