-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (73 loc) · 1.7 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"fmt"
"io/ioutil"
"strings"
"strconv"
)
func parseFile(filePath string) ([][]int) {
data, _ := ioutil.ReadFile(filePath)
lines := strings.Split(string(data), "\n")
var result [][]int
for _, s := range lines {
var historyValues []int
for _, substr := range strings.Fields(s) {
val, _ := strconv.Atoi(substr) // Conversion to int, ignoring errors
historyValues = append(historyValues, val)
}
result = append(result, historyValues)
}
return result;
}
func allZero(nums []int) bool {
for _, num := range nums {
if num != 0 {
return false
}
}
return true
}
func calcDifferences(nums []int) []int {
differences := make([]int, len(nums)-1)
for i := 0; i < len(nums)-1; i++ {
differences[i] = nums[i+1] - nums[i]
}
return differences
}
func predictNextValue(history []int) (int) {
if (allZero(history)) {
return 0
}
differences := calcDifferences(history)
next := predictNextValue(differences)
lastValue := history[len(history)-1]
return lastValue + next
}
func predictPreviousValue(history []int) (int) {
if (allZero(history)) {
return 0
}
differences := calcDifferences(history)
next := predictPreviousValue(differences)
lastValue := history[0]
return lastValue - next
}
func solve(input [][]int) {
var sum = 0
for _, history := range input {
sum += predictNextValue(history)
}
fmt.Println(sum)
}
func solve2(input [][]int) {
var sum = 0
for _, history := range input {
sum += predictPreviousValue(history)
}
fmt.Println(sum)
}
func main() {
input := parseFile("input")
solve(input)
solve2(input)
}