From f40f2356d34eb70c564962a858fbbc2cf5b6ebdf Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Tue, 22 Dec 2020 09:45:19 -0800 Subject: [PATCH] [2020][ruby][22.x] --- 2020/ruby/day_22.rb | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 2020/ruby/day_22.rb diff --git a/2020/ruby/day_22.rb b/2020/ruby/day_22.rb new file mode 100644 index 0000000..76c76b7 --- /dev/null +++ b/2020/ruby/day_22.rb @@ -0,0 +1,46 @@ +require "set" + +decks = ARGF.read.split("\n\n").map {|players| players.split("\n")[1..].map(&:to_i) } + +# part one + +# until decks.any?(&:empty?) +# p decks +# top_cards = decks.map(&:shift) +# fail if top_cards.tally.size == 1 + +# if top_cards.first > top_cards.last +# decks.first.concat(top_cards) +# else +# decks.last.concat(top_cards.reverse) +# end +# end + +SEEN = Set.new +def recursive_combat!(decks) + until decks.any?(&:empty?) + return 0 if SEEN.include?(decks) + SEEN << decks + + top_cards = decks.map(&:shift) + winner = if decks.zip(top_cards).all? {|d,tc| d.size >= tc } + recursive_combat!(decks.zip(top_cards).map {|d,tc| d[0,tc] }) + elsif top_cards.first > top_cards.last + 0 + else + 1 + end + + if winner == 0 + decks.first.concat(top_cards) + else + decks.last.concat(top_cards.reverse) + end + end + + decks.index {|d| !d.empty? } +end + +recursive_combat!(decks) + +p decks.flatten.reverse.map.with_index {|v,i| v * (i+1) }.sum