solved part 2

master
Jeff Yates 2020-12-08 17:00:50 -05:00
parent aeb838b832
commit f054a23480
1 changed files with 28 additions and 0 deletions

28
day07/solution02.rb Executable file
View File

@ -0,0 +1,28 @@
#!/bin/env ruby
def can_hold? (bags, color)
parents = bags.map { |bag| bag[1..].
map { |child| bag[0] if child.include?(color)}
}.flatten.compact
if parents.any?
parents += parents.map { |col| can_hold?(bags, col) }
end
parents.flatten
end
def bags_inside (bags, color, num)
total = bags.map { |bag| bag[1..] if bag[0].include?(color) }
.flatten.compact.map { |item| [num * item[0].to_i,item[2..]] if item[0].to_i != 0}
if total.any?
total += total.map { |item| bags_inside(bags, item[1], item[0]) if item != nil}
end
total.flatten.compact
end
bags = File.readlines('./input').map { |line| line.delete('.').strip.split('contain').
map { |item| item.strip.split(',')}.flatten
}
bags.map { |line| line.map { |str| str.slice!('bags') }}
bags.map { |line| line.map { |str| str.slice!('bag') }}
bags.map { |line| line.map { |str| str.strip! }}
p bags_inside(bags, 'shiny gold', 1).select { |item| item.is_a?(Integer)}.sum