28 lines
987 B
Ruby
Executable File
28 lines
987 B
Ruby
Executable File
#!/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 |