-
Notifications
You must be signed in to change notification settings - Fork 0
/
day09.go
79 lines (66 loc) · 1.25 KB
/
day09.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
package main
import (
_ "embed"
"fmt"
"slices"
"strconv"
"strings"
)
//go:embed input.txt
var input string
func parseValues(values []int, line string) {
line += " "
var start, vIndex int
for i := 0; i < len(line); i++ {
if line[i] == ' ' {
n, _ := strconv.Atoi(line[start:i])
values[vIndex] = n
start = i + 1
vIndex++
}
}
}
func nextValue(v []int) int {
var nv int
var az bool
for !az {
az = true
nv += v[len(v)-1]
for i := 1; i < len(v); i++ {
v[i-1] = v[i] - v[i-1]
if v[i-1] != 0 {
az = false
}
}
v = v[:len(v)-1]
}
return nv
}
func part1(input string) int {
lines := strings.Split(input, "\n")
length := len(strings.Split(lines[0], " "))
values := make([]int, length)
var sum int
for _, line := range lines {
parseValues(values, line)
sum += nextValue(values)
}
return sum
}
func part2(input string) int {
lines := strings.Split(input, "\n")
length := len(strings.Split(lines[0], " "))
values := make([]int, length)
var sum int
for _, line := range lines {
parseValues(values, line)
slices.Reverse(values)
sum += nextValue(values)
}
return sum
}
func main() {
fmt.Println("--- 2023 day 09 answer ---")
fmt.Println("part 1:\t", part1(input))
fmt.Println("part 2:\t", part2(input))
}