From a80aa90a8b47a3e6be04a4ee1ebb11b3dd29494f Mon Sep 17 00:00:00 2001 From: Nat Lasseter Date: Sat, 8 Dec 2018 17:36:38 +0000 Subject: [day08] done --- day08/part2 | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100755 day08/part2 (limited to 'day08/part2') diff --git a/day08/part2 b/day08/part2 new file mode 100755 index 0000000..94c2415 --- /dev/null +++ b/day08/part2 @@ -0,0 +1,36 @@ +#!/usr/bin/env ruby + +def parse_tree(input, start) + num_children = input[start] + num_metadata = input[start + 1] + + children = [] + next_index = start + 2 + while num_children > 0 do + sum, endindex = parse_tree(input, next_index) + children << sum + next_index = endindex + 1 + num_children -= 1 + end + + value = 0 + if children.empty? + while num_metadata > 0 do + value += input[next_index] + next_index += 1 + num_metadata -= 1 + end + else + while num_metadata > 0 do + i = input[next_index] + value += children[i - 1] if i <= children.length + next_index += 1 + num_metadata -= 1 + end + end + return [ value, next_index - 1 ] +end + +input = gets.chomp.split.map(&:to_i) + +puts parse_tree(input, 0)[0] -- cgit v1.2.1