-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
72 lines (58 loc) · 1.41 KB
/
main.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
package main
import (
"fmt"
aoc "github.com/shraddhaag/aoc/library"
)
func main() {
input := aoc.ReadFileLineByLine("input.txt")
fmt.Println("answer for part 1: ", findSumOfExtensions(input, extendEnd))
fmt.Println("answer for part 2: ", findSumOfExtensions(input, extendBeginning))
}
func findSumOfExtensions(input []string, extend func([]int, int) int) int {
sum := 0
for _, line := range input {
sum += evaluateHistory(line, extend)
}
return sum
}
func evaluateHistory(input string, extend func([]int, int) int) int {
inputSlice := aoc.FetchSliceOfIntsInString(input)
next := extend(inputSlice, predictNext(inputSlice, extend))
return next
}
func extendEnd(inputSlice []int, last int) int {
return inputSlice[len(inputSlice)-1] + last
}
func extendBeginning(inputSlice []int, last int) int {
return inputSlice[0] - last
}
func predictNext(input []int, extend func([]int, int) int) int {
if isAllZero(input) {
return 0
}
if len(input) <= 1 {
return input[0]
}
diff := findDiff(input)
last := predictNext(diff, extend)
return extend(diff, last)
}
func findDiff(input []int) []int {
if len(input) <= 1 {
return input
}
output := []int{}
for i := 0; i < len(input)-1; i++ {
output = append(output, input[i+1]-input[i])
}
return output
}
func isAllZero(input []int) bool {
output := 0
for i := 0; i < len(input); i++ {
if input[i] == 0 {
output++
}
}
return output == len(input)
}