Add solution for day 8.
This commit is contained in:
parent
b8a8a2155f
commit
c132a28232
49
day8.cr
Normal file
49
day8.cr
Normal file
|
@ -0,0 +1,49 @@
|
||||||
|
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
|
Loading…
Reference in New Issue
Block a user