From 35b1015882f91e4fa3f6f968d8761df43b54e599 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Mon, 21 Dec 2020 09:32:59 -0800 Subject: [PATCH] [2020][ruby][21.2] --- 2020/ruby/day_21.rb | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/2020/ruby/day_21.rb b/2020/ruby/day_21.rb index 0e82d40..8de9998 100644 --- a/2020/ruby/day_21.rb +++ b/2020/ruby/day_21.rb @@ -10,6 +10,7 @@ foods = ARGF.read } all_ingredients = foods.map(&:ingredients).inject(&:|) +all_allergens = foods.map(&:allergens).inject(&:|) no_allergens = all_ingredients.select {|ingredient| possible_allergens = foods @@ -22,5 +23,17 @@ no_allergens = all_ingredients.select {|ingredient| } } -p foods.map {|f| f.ingredients.count {|i| no_allergens.include?(i) }}.sum +# part one +# p foods.map {|f| f.ingredients.count {|i| no_allergens.include?(i) }}.sum +known, unknown = all_allergens.map {|a| + [a, foods.select {|f| f.allergens.include?(a) }.map(&:ingredients).inject(&:&) ] +}.to_h.partition {|_,v| v.size == 1 }.map(&:to_h) + +until unknown.empty? + unknown.transform_values! {|v| v - known.values.inject(&:|) } + new_known, unknown = unknown.partition {|_,v| v.size == 1 }.map(&:to_h) + known.merge!(new_known) +end + +p known.transform_values {|v| v.to_a.first }.sort_by(&:first).map(&:last).join(?,)