diff --git a/2018/day08-1.go b/2018/day08-1.go index 082a1ce..f4058f8 100644 --- a/2018/day08-1.go +++ b/2018/day08-1.go @@ -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) diff --git a/2018/day08-2.go b/2018/day08-2.go new file mode 100644 index 0000000..2a469ac --- /dev/null +++ b/2018/day08-2.go @@ -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 +} diff --git a/2018/internal/day08/tree.go b/2018/internal/day08/tree.go index 47da31a..5772a75 100644 --- a/2018/internal/day08/tree.go +++ b/2018/internal/day08/tree.go @@ -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