class Day06
def initialize(filename)
@filename = filename
end
def solve
off_balance_trees = 0
File.open(@filename).each("\r\n\r\n") do |tree|
trunk = 0
left = 0
right = 0
tree.strip.each_line.with_index do |line, i|
if i.zero?
# first line is trunk
trunk = line.to_i
elsif i == 1
# second line is left and right branch weight
l, r = line.split(' ')
left = l.to_i
right = r.to_i
elsif i == 2
# third line is 2 left and 2 right ornament weights
line.each_line(' ').with_index do |weight, i|
if i < 2
left += weight.to_i
elsif i < 4
right += weight.to_i
end
end
end
end
off_balance_trees += trunk + left + right if (left - right).abs > 1
end.close
puts "Off balance tree weight: #{off_balance_trees}"
end
end
# Expects the input file to be named 06.txt and in the current working directory
if __FILE__ == $PROGRAM_NAME
challenge = Day06.new('06.txt')
challenge.solve
end
As the elves are busy making Christmas trees Mrs. Santa comes to look over the finished products. She notices that some of the Christmas trees are leaning one way or the other while some are straight as an arrow. She consults with the Head Elf and confirms that there is an issue in the production of Christmas trees. Help them figure out which trees are off balance so they know how much material is going to need to be recycled.
The elves today were making simple trees with only 2 branches and up to 2 ornaments on each branch. Each part of the tree has a specific weight.
Mrs. Santa has noted that the trees only start to lean over if the branches weights are off by more than 1.
The trees are given as input in the following format:
9
6 6
1 2 2 1
8
4 5
2 2 2 2
9
5 6
1 2 2 2
8
6 6
2 2 _ _
Each tree is separated by a blank line. Each tree is defined as such:
_ it means there is a missing ornament so don’t count itProblem: Calculate the total weight of all the trees in trees.txt that are off balance. For the example above the total weight of off balance trees (the last 2) is 51.