-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09p1.go
63 lines (53 loc) · 1.31 KB
/
09p1.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
package main
import (
"fmt"
"strconv"
"strings"
"aoc2023/utils"
)
func D09P1() {
lines := utils.ReadLines("./inputs/09.txt")
oasisHistory := parseOasisHistory(lines)
nextValueSum := 0
for _, line := range oasisHistory {
nextValue := predictNextOasisValue(line, false)
nextValueSum += nextValue
}
fmt.Printf("The sum of predicted next OASIS values is %d\n", nextValueSum)
}
func parseOasisHistory(lines []string) [][]int {
oasisHistory := [][]int{}
for _, line := range lines {
lineHistory := []int{}
historyValues := strings.Split(line, " ")
for _, historyValue := range historyValues {
value, _ := strconv.Atoi(historyValue)
lineHistory = append(lineHistory, value)
}
oasisHistory = append(oasisHistory, lineHistory)
}
return oasisHistory
}
func predictNextOasisValue(history []int, partTwo bool) int {
historyDiffs := []int{}
for i, value := range history {
if i == 0 {
continue
}
historyDiffs = append(historyDiffs, value-history[i-1])
}
historyTotal := 0
for _, value := range historyDiffs {
historyTotal += value
}
if historyTotal == 0 {
if partTwo {
return history[0]
}
return history[len(history)-1]
}
if partTwo {
return history[0] - predictNextOasisValue(historyDiffs, partTwo)
}
return predictNextOasisValue(historyDiffs, partTwo) + history[len(history)-1]
}