-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday11.go
89 lines (78 loc) · 1.54 KB
/
day11.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
80
81
82
83
84
85
86
87
88
89
package main
import (
"fmt"
"io"
"os"
"strconv"
"strings"
)
type Stone struct {
n int
nStr string
}
func evenDigits(n Stone) bool {
return len(n.nStr)%2 == 0
}
func leftRight(n Stone) []Stone {
left := n.nStr[:len(n.nStr)/2]
right := n.nStr[len(n.nStr)/2:]
return []Stone{StoneFromStr(left), StoneFromStr(right)}
}
var One = Stone{1, "1"}
func StoneFromNum(n int) Stone {
return Stone{n, strconv.Itoa(n)}
}
func StoneFromStr(s string) Stone {
n, _ := strconv.Atoi(s)
return Stone{n, strings.TrimLeft(s, "0")}
}
type CacheKey struct {
stone Stone
depth int
}
var cache = make(map[CacheKey]int)
func ApplyRules(v Stone, depth int) int {
// fmt.Println(v, depth)
if depth == 0 {
return 1
}
cacheKey := CacheKey{v, depth}
if r, ok := cache[cacheKey]; ok {
return r
}
r := 0
switch {
case v.n == 0:
r = ApplyRules(One, depth-1)
case evenDigits(v):
lr := leftRight(v)
r = ApplyRules(lr[0], depth-1) + ApplyRules(lr[1], depth-1)
default:
r = ApplyRules(StoneFromNum(2024*v.n), depth-1)
}
cache[cacheKey] = r
return r
}
func main() {
// read input list
data, _ := io.ReadAll(os.Stdin)
inp := strings.TrimSpace(string(data))
inpList := strings.Split(inp, " ")
// Split into list of ints.
stones := make([]Stone, 0, len(inpList))
for _, n := range inpList {
stones = append(stones, StoneFromStr(n))
}
// Part1
sum := 0
for v := range stones {
sum += ApplyRules(stones[v], 25)
}
fmt.Println("Part 1", sum)
// Part2
sum = 0
for v := range stones {
sum += ApplyRules(stones[v], 75)
}
fmt.Println("Part 2", sum)
}