-
Notifications
You must be signed in to change notification settings - Fork 3
/
8.rb
executable file
·63 lines (49 loc) · 1.18 KB
/
8.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env ruby
require 'pp'
FILENAME = 'input.txt'
#FILENAME = 'input_small.txt'
nums = []
File.readlines(FILENAME).each do |line|
nums = line.split(' ')
nums = nums.map(&:to_i)
break
end
def build_child(nums)
node = {}
num_children = nums.shift
num_metadata = nums.shift
node[:num_children] = num_children
node[:num_metadata] = num_metadata
children = []
metadata = []
1.upto(num_children) { |child_i| children.push(build_child(nums)) }
node[:children] = children
1.upto(num_metadata) { |metadata_i| metadata.push(nums.shift) }
node[:metadata] = metadata
node
end
def add_all_metadata(tree)
child_sum = tree[:children].map { |x| add_all_metadata(x) }.sum
tree[:metadata].sum + child_sum
end
def node_value(tree)
#puts 'enter node value'
#pp tree
if (tree[:children].length == 0)
#puts "return simple sum #{tree[:metadata].sum}"
return tree[:metadata].sum
end
rv = 0
tree[:metadata].each do |i|
rv += node_value(tree[:children][i - 1]) if tree[:children][i - 1] != nil
end
#puts "return return value #{rv}"
rv
end
tree = build_child(nums)
#pp tree
pp '--'
total = add_all_metadata(tree)
pp total
pp 'part2---'
pp node_value(tree)