require'set'bag_descriptions=[]File.readlines('07.txt').eachdo|line|bag_type=line.match('\A(.*?) bags')[1]contents=[]unlessline.match('contain no other bags')line.scan(/(\d+) (.*?) bags?/).eachdo|count,color|contents.push[color,count]endendbag_descriptions.push({"bag_type"=>bag_type,"contents"=>contents.to_h})enddefscan_for_possible_containers(bag_descriptions,previous_possible_containers)new_containers=Set.newbag_descriptions.eachdo|bag_description|# Direct container of shiny gold bagsifbag_description['contents'].include?'shiny gold'# Don't need to check if already present because Set class is usednew_containers.addbag_description['bag_type']end# Indirect containers of shiny gold bagsunlessprevious_possible_containers.intersection(Set.newbag_description['contents'].keys).empty?# Again, no need to check if already presentnew_containers.addbag_description['bag_type']endendnew_containersendprevious_possible_containers=Set.new# Initial scancurrent_possible_containers=scan_for_possible_containers(bag_descriptions,previous_possible_containers)# Keep iterating until all possible choices are exhausteduntilprevious_possible_containers==current_possible_containersprevious_possible_containers=current_possible_containerscurrent_possible_containers=scan_for_possible_containers(bag_descriptions,previous_possible_containers)endputscurrent_possible_containers.length
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Ruby, part 1. Kinda ugly, but effective: