-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart_2.go
88 lines (73 loc) · 1.76 KB
/
part_2.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
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func PreviousSumOfExtraPolatedValues() {
histories := make([][]int, 0)
file, err := os.Open("input.txt")
if err != nil {
fmt.Printf("error reading input.txt: %v\n", err)
os.Exit(1)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
values := parseIntegers(line)
histories = append(histories, values)
}
if err := scanner.Err(); err != nil {
fmt.Printf("error reading input.txt: %v\n", err)
os.Exit(1)
}
extrapolatedValues := make([]int, 0)
for _, history := range histories {
subLists := [][]int{history}
allZeroes := false
for !allZeroes {
sublist := make([]int, 0)
for i := 0; i < len(subLists[len(subLists)-1])-1; i++ {
difference := subLists[len(subLists)-1][i+1] - subLists[len(subLists)-1][i]
sublist = append(sublist, difference)
}
allZeroes = allZeroesInSlices(sublist)
subLists = append(subLists, sublist)
}
subLists[len(subLists)-1] = append([]int{0}, subLists[len(subLists)-1]...)
for i := len(subLists) - 2; i >= 0; i-- {
extrapolatedValue := subLists[i][0] - subLists[i+1][0]
subLists[i] = append([]int{extrapolatedValue}, subLists[i]...)
}
extrapolatedValues = append(extrapolatedValues, subLists[0][0])
}
ans := sums(extrapolatedValues)
fmt.Println(ans)
}
func parseIntegers(input string) []int {
var nums []int
fields := strings.Fields(input)
for _, field := range fields {
num, _ := strconv.Atoi(field)
nums = append(nums, num)
}
return nums
}
func allZeroesInSlices(nums []int) bool {
for _, num := range nums {
if num != 0 {
return false
}
}
return true
}
func sums(nums []int) int {
result := 0
for _, num := range nums {
result += num
}
return result
}