solved part 2

master
Jeff Yates 2 years ago
parent aeb838b832
commit f054a23480
  1. 28
      day07/solution02.rb

@ -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
Loading…
Cancel
Save