Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.83 KB | None | 0 0
  1. require 'set'
  2.  
  3. @p1 = []
  4. @p2 = []
  5.  
  6. input = File.readlines("day22.txt").collect(&:chomp).each do |line|
  7.     next if line.empty?
  8.     next @deck = @p1 if line == "Player 1:"
  9.     next @deck = @p2 if line == "Player 2:"    
  10.     @deck << line.to_i
  11. end
  12.  
  13. def play_combat(p1, p2)
  14.     until p1.empty? || p2.empty?
  15.         p1_draw, p2_draw = p1.shift, p2.shift
  16.         if p1_draw > p2_draw
  17.             p1 += [p1_draw, p2_draw]
  18.         else
  19.             p2 += [p2_draw, p1_draw]
  20.         end
  21.     end
  22.  
  23.     return p2.empty? ? p1 : p2
  24. end
  25.  
  26. def play_recursive_combat(p1, p2, recursive = false)
  27.     rounds = Set.new
  28.     until p1.empty? || p2.empty?
  29.         this_round = [p1, p2].hash
  30.         return [:p1, p1] if rounds.include?(this_round)
  31.         rounds << this_round
  32.         p1_draw, p2_draw = p1.shift, p2.shift
  33.         result =
  34.             if p1.size >= p1_draw && p2.size >= p2_draw
  35.                 play_recursive_combat(p1.take(p1_draw),
  36.                                       p2.take(p2_draw),
  37.                                       true).first
  38.             else
  39.                 p1_draw > p2_draw ? :p1 : :p2
  40.             end
  41.         if result == :p1
  42.             p1 += [p1_draw, p2_draw]
  43.         else
  44.             p2 += [p2_draw, p1_draw]
  45.         end
  46.     end
  47.  
  48.     return p2.empty? ? [:p1, p1] : [:p2, p2]
  49. end
  50.  
  51. def calculate_score(deck)    
  52.     return score = deck.reverse.collect.with_index do |card, idx|
  53.         card * (idx + 1)
  54.     end.sum
  55. end
  56.  
  57. t1 = Time.now.utc
  58.  
  59. puts format("Part One: %<score>s (%<time>s seconds)",
  60.             score: calculate_score(play_combat(@p1.dup, @p2.dup)),
  61.             time: Time.now.utc - t1)
  62.  
  63. t2 = Time.now.utc
  64.  
  65. puts format("Part Two: %<score>s (%<time>s seconds)",
  66.             score: calculate_score(play_recursive_combat(@p1.dup, @p2.dup).last),
  67.             time: Time.now.utc - t2)
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement