Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'set'
- @p1 = []
- @p2 = []
- input = File.readlines("day22.txt").collect(&:chomp).each do |line|
- next if line.empty?
- next @deck = @p1 if line == "Player 1:"
- next @deck = @p2 if line == "Player 2:"
- @deck << line.to_i
- end
- def play_combat(p1, p2)
- until p1.empty? || p2.empty?
- p1_draw, p2_draw = p1.shift, p2.shift
- if p1_draw > p2_draw
- p1 += [p1_draw, p2_draw]
- else
- p2 += [p2_draw, p1_draw]
- end
- end
- return p2.empty? ? p1 : p2
- end
- def play_recursive_combat(p1, p2, recursive = false)
- rounds = Set.new
- until p1.empty? || p2.empty?
- this_round = [p1, p2].hash
- return [:p1, p1] if rounds.include?(this_round)
- rounds << this_round
- p1_draw, p2_draw = p1.shift, p2.shift
- result =
- if p1.size >= p1_draw && p2.size >= p2_draw
- play_recursive_combat(p1.take(p1_draw),
- p2.take(p2_draw),
- true).first
- else
- p1_draw > p2_draw ? :p1 : :p2
- end
- if result == :p1
- p1 += [p1_draw, p2_draw]
- else
- p2 += [p2_draw, p1_draw]
- end
- end
- return p2.empty? ? [:p1, p1] : [:p2, p2]
- end
- def calculate_score(deck)
- return score = deck.reverse.collect.with_index do |card, idx|
- card * (idx + 1)
- end.sum
- end
- t1 = Time.now.utc
- puts format("Part One: %<score>s (%<time>s seconds)",
- score: calculate_score(play_combat(@p1.dup, @p2.dup)),
- time: Time.now.utc - t1)
- t2 = Time.now.utc
- puts format("Part Two: %<score>s (%<time>s seconds)",
- score: calculate_score(play_recursive_combat(@p1.dup, @p2.dup).last),
- time: Time.now.utc - t2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement