You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
833 B
Go

package day9
import (
"fmt"
"slices"
"gitea.paas.celticinfo.fr/oabrivard/aoc2023/utils"
)
func SumLastTerms(lines []string, reverse bool) int {
result := 0
for _, line := range lines {
values := utils.ParseIntArray(line, " ")
if reverse {
slices.Reverse(values)
}
stack := [][]int{}
stack = append(stack, values)
for {
top := stack[len(stack)-1]
allZeros := utils.Fold(true, top, func(acc bool, curr int) bool { return acc && curr == 0 })
if allZeros {
break
}
newTop := make([]int, len(top)-1)
for i := 1; i < len(top); i++ {
newTop[i-1] = top[i-1] - top[i]
}
stack = append(stack, newTop)
}
newVal := stack[len(stack)-1][0]
for i := len(stack) - 2; i >= 0; i-- {
newVal = stack[i][0] + newVal
}
fmt.Println(newVal)
result += newVal
}
return result
}