aboutsummaryrefslogtreecommitdiff
path: root/day08/part1
blob: ef22cfabe130acc03256ab0ccf5fd5a11e1d3bf1 (plain)
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
#!/usr/bin/env ruby

def parse_tree(input, start)
  num_children = input[start]
  num_metadata = input[start + 1]

  next_index = start + 2
  sums = 0
  while num_children > 0 do
    sum, endindex = parse_tree(input, next_index)
    sums += sum
    next_index = endindex + 1
    num_children -= 1
  end

  metadata = 0
  while num_metadata > 0 do
    metadata += input[next_index]
    next_index += 1
    num_metadata -= 1
  end

  return [ sums + metadata, next_index - 1]
end

input = gets.chomp.split.map(&:to_i)

puts parse_tree(input, 0)[0]