-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
77 lines (63 loc) · 1.35 KB
/
main.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
package main
import (
_ "embed"
"fmt"
"regexp"
"strconv"
"strings"
)
//go:embed input.txt
var input string
/**
* Day 9: Mirage Maintenance - Part 1
* url: https://adventofcode.com/2023/day/9
*/
func main() {
sum := 0
for _, s := range strings.Split(strings.TrimSpace(input), "\n") {
line := parseNumbers(strings.TrimSpace(s))
tower := generateTower(line)
next := extrapolateNextValue(tower)
sum += next
}
fmt.Println("Part 1 =", sum)
}
func extrapolateNextValue(tower [][]int) int {
lastLine := len(tower) - 1
tower[lastLine] = append(tower[lastLine], 0)
for i := len(tower) - 2; i >= 0; i-- {
idx := len(tower[i]) - 1
tower[i] = append(tower[i], tower[i+1][idx]+tower[i][idx])
}
return tower[0][len(tower[0])-1]
}
func generateTower(num []int) [][]int {
tower := [][]int{}
tower = append(tower, num)
for {
row := tower[len(tower)-1]
nextRow := []int{}
finish := true
for i := 0; i < len(row)-1; i++ {
diff := row[i+1] - row[i]
if diff != 0 {
finish = false
}
nextRow = append(nextRow, diff)
}
tower = append(tower, nextRow)
if finish {
break
}
}
return tower
}
func parseNumbers(s string) []int {
re := regexp.MustCompile(`-?\d+`)
numbers := []int{}
for _, val := range re.FindAllStringSubmatch(s, -1) {
num, _ := strconv.Atoi(val[0])
numbers = append(numbers, num)
}
return numbers
}