-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
112 lines (92 loc) · 1.81 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"io"
lib "github.com/teivah/advent-of-code"
)
func fs1(input io.Reader) int {
s := lib.ReaderToString(input)
var numbers []int
for i := 0; i < len(s); i++ {
j := i + 1
for ; j < len(s); j++ {
if s[j] >= '0' && s[j] <= '9' {
continue
}
break
}
numbers = append(numbers, lib.StringToInt(s[i:j]))
i = j
}
root, _ := toNode(numbers, 0)
return sum(*root)
}
func sum(node Node) int {
v := node.metadataSum
for _, child := range node.children {
v += sum(child)
}
return v
}
type Node struct {
childNodes int
metadata int
children []Node
metadataSum int
metadataEntries []int
}
func toNode(numbers []int, i int) (*Node, int) {
if i >= len(numbers) {
return nil, i
}
childNodes := numbers[i]
metadata := numbers[i+1]
node := Node{childNodes: childNodes, metadata: metadata}
i += 2
for j := 0; j < childNodes; j++ {
child, newI := toNode(numbers, i)
if child == nil {
continue
}
node.children = append(node.children, *child)
i = newI
}
metadataSum := 0
for j := 0; j < metadata; j++ {
metadataSum += numbers[i]
node.metadataEntries = append(node.metadataEntries, numbers[i])
i++
}
node.metadataSum = metadataSum
return &node, i
}
func fs2(input io.Reader) int {
s := lib.ReaderToString(input)
var numbers []int
for i := 0; i < len(s); i++ {
j := i + 1
for ; j < len(s); j++ {
if s[j] >= '0' && s[j] <= '9' {
continue
}
break
}
numbers = append(numbers, lib.StringToInt(s[i:j]))
i = j
}
root, _ := toNode(numbers, 0)
return value(*root)
}
func value(node Node) int {
if node.childNodes == 0 {
return node.metadataSum
}
sum := 0
for _, entry := range node.metadataEntries {
entry--
if entry >= node.childNodes {
continue
}
sum += value(node.children[entry])
}
return sum
}