Day 8.2 solution.

This commit is contained in:
Anna Rose 2018-12-10 21:15:33 -05:00
parent 4d567425a7
commit 656e975cb1
No known key found for this signature in database
GPG Key ID: 8D9ACA841015C59A
3 changed files with 45 additions and 4 deletions

View File

@ -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
View 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
}

View File

@ -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