81 lines
1.3 KiB
Go
81 lines
1.3 KiB
Go
package day09
|
|
|
|
import (
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func Part1(input string) int {
|
|
lines := strings.Split(input, "\r\n")
|
|
total := 0
|
|
for _, line := range lines {
|
|
var intSeq []int
|
|
seq := strings.Split(line, " ")
|
|
for _, i := range seq {
|
|
num, _ := strconv.Atoi(i)
|
|
intSeq = append(intSeq, num)
|
|
}
|
|
total += extrapolate1(intSeq)
|
|
}
|
|
return total
|
|
}
|
|
|
|
func Part2(input string) int {
|
|
lines := strings.Split(input, "\r\n")
|
|
total := 0
|
|
for _, line := range lines {
|
|
var intSeq []int
|
|
seq := strings.Split(line, " ")
|
|
for _, i := range seq {
|
|
num, _ := strconv.Atoi(i)
|
|
intSeq = append(intSeq, num)
|
|
}
|
|
total += extrapolate2(intSeq)
|
|
}
|
|
return total
|
|
}
|
|
|
|
func extrapolate1(array []int) int {
|
|
allZeros := true
|
|
for _, x := range array {
|
|
if x != 0 {
|
|
allZeros = false
|
|
break
|
|
}
|
|
}
|
|
|
|
if allZeros {
|
|
return 0
|
|
}
|
|
|
|
deltas := make([]int, len(array)-1)
|
|
for i := 0; i < len(array)-1; i++ {
|
|
deltas[i] = array[i+1] - array[i]
|
|
}
|
|
|
|
diff := extrapolate1(deltas)
|
|
return array[len(array)-1] + diff
|
|
}
|
|
|
|
func extrapolate2(array []int) int {
|
|
allZeros := true
|
|
for _, x := range array {
|
|
if x != 0 {
|
|
allZeros = false
|
|
break
|
|
}
|
|
}
|
|
|
|
if allZeros {
|
|
return 0
|
|
}
|
|
|
|
deltas := make([]int, len(array)-1)
|
|
for i := 0; i < len(array)-1; i++ {
|
|
deltas[i] = array[i+1] - array[i]
|
|
}
|
|
|
|
diff := extrapolate2(deltas)
|
|
return array[0] - diff
|
|
}
|