AdventOfCode-2018/day8.cr

50 lines
965 B
Crystal
Raw Permalink Normal View History

2018-12-07 21:19:42 -08:00
require "./common.cr"
lines = File.read("day8_input").split("\n")
lines.pop
class Node
getter children : Array(Node)
getter metadata : Array(Int32)
def initialize(@children : Array(Node), @metadata : Array(Int32))
end
def sum
return metadata.sum + children.map(&.sum.as Int32).sum
end
def value
return metadata.sum if children.empty?
metadata.map do |meta|
next 0 unless child = children[meta - 1]?
next child.value
end.sum
end
end
def parse(numbers, index = 0)
child_count = numbers[index]
index += 1
meta_count = numbers[index]
index += 1
children = Array(Node).new
child_count.times do |count|
child, index = parse(numbers, index)
children << child
end
meta = numbers[index...(index + meta_count)]
index += meta_count
node = Node.new children, meta
return {node, index}
end
numbers = lines[0].split(" ").map &.to_i32
tree = parse(numbers)
puts tree[0].sum
puts tree[0].value