Add solution for day 9 part 2

master
Nick Krichevsky 2023-12-09 13:33:54 -05:00
parent 587d832294
commit f3b957628e
1 changed files with 13 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import (
"fmt"
"io"
"os"
"slices"
"strconv"
"strings"
)
@ -35,6 +36,7 @@ func main() {
}
fmt.Printf("Part 1: %d\n", part1(histories))
fmt.Printf("Part 2: %d\n", part2(histories))
}
func part1(histories [][]int) int {
@ -46,6 +48,17 @@ func part1(histories [][]int) int {
return total
}
func part2(histories [][]int) int {
total := 0
for _, history := range histories {
reversedHistory := slices.Clone(history)
slices.Reverse(reversedHistory)
total += predictNextValue(reversedHistory)
}
return total
}
// predictNextValue calculates the next item in the sequence by using the nth differences
func predictNextValue(history []int) int {
if allEqual(history, 0) {