Day 8.2 solution.
This commit is contained in:
parent
4d567425a7
commit
656e975cb1
|
@ -14,10 +14,7 @@ func main() {
|
|||
}
|
||||
|
||||
func sumMetadata(node *day08.Node) int {
|
||||
sum := 0
|
||||
for _, v := range node.Metadata {
|
||||
sum += v
|
||||
}
|
||||
sum := node.SumMetadata()
|
||||
|
||||
for _, child := range node.Children {
|
||||
sum += sumMetadata(child)
|
||||
|
|
36
2018/day08-2.go
Normal file
36
2018/day08-2.go
Normal file
|
@ -0,0 +1,36 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"internal/day08"
|
||||
"internal/util"
|
||||
)
|
||||
|
||||
func main() {
|
||||
data := util.ReadInputInts()
|
||||
root := day08.BuildTree(data)
|
||||
fmt.Println(generateChecksum(root))
|
||||
}
|
||||
|
||||
func generateChecksum(node *day08.Node) int {
|
||||
// If a node has no child nodes, its value is the sum of its metadata entries.
|
||||
if len(node.Children) == 0 {
|
||||
return node.SumMetadata()
|
||||
}
|
||||
|
||||
// if a node does have child nodes, the metadata entries become (1-indexed) indexes
|
||||
// which refer to those child nodes.
|
||||
// The value of the node is the sum of the values of its children.
|
||||
value := 0
|
||||
for _, md := range node.Metadata {
|
||||
// Skip invalid metadata entries
|
||||
if md == 0 || md > len(node.Children) {
|
||||
continue
|
||||
}
|
||||
|
||||
value += generateChecksum(node.Children[md-1])
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
|
@ -5,6 +5,14 @@ type Node struct {
|
|||
Metadata []int
|
||||
}
|
||||
|
||||
func (node Node) SumMetadata() int {
|
||||
sum := 0
|
||||
for _, v := range node.Metadata {
|
||||
sum += v
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
func BuildTree(data []int) *Node {
|
||||
root, _ := buildTreeR(data, 0)
|
||||
return root
|
||||
|
|
Loading…
Reference in New Issue
Block a user