Skip to content

Instantly share code, notes, and snippets.

@pwightman
Created June 14, 2012 16:53
Show Gist options
  • Save pwightman/2931464 to your computer and use it in GitHub Desktop.
Save pwightman/2931464 to your computer and use it in GitHub Desktop.
class WrongNumberOfPlayersError < StandardError ; end
class NoSuchStrategyError < StandardError ; end
def rps_game_winner(game)
raise WrongNumberOfPlayersError unless game.length == 2
player1 = game[0]
player2 = game[1]
player1_play = player1[1]
player2_play = player2[1]
plays = ["R", "P", "S"]
raise NoSuchStrategyError if !plays.include?(player1_play) || !plays.include?(player2_play)
# An array of two-element arrays:
# 1) Exhaustive list of possible game outcomes
# 2) 0 or 1, indicating the index of the winning play
strats = []
strats << [["R", "S"], 0]
strats << [["R", "R"], 0]
strats << [["R", "P"], 1]
strats << [["P", "P"], 0]
strats << [["P", "S"], 1]
strats << [["P", "R"], 0]
strats << [["S", "S"], 0]
strats << [["S", "R"], 1]
strats << [["S", "P"], 0]
# Create an array that we'll match against the strategies
# in the strats array, e.g. ["R", "S"]
strat = [player1_play, player2_play]
# Find the matching strategy from strat, and return the correct
# player using the index
strats.each do |s|
return game[s[1]] if strat == s[0]
end
# A much simpler solution than this would be to just back for the
# 3 cases where you return 1 in an if statement, else return 0
raise "Should not get here"
end
def rps_tournament_winner game
# Recurse until you've drilled down to the first actual game
play1 = game[0]
play1 = rps_tournament_winner play1 if play1[0].class == Array
play2 = game[1]
play2 = rps_tournament_winner play2 if play2[0].class == Array
# You're drilled down to an actual game at this point, so
# compute the winner and let the recursion unroll.
rps_game_winner([play1, play2])
end
tourn_arr =
[
[
[ ["Armando", "P"], ["Dave", "S"] ],
[ ["Richard", "R"], ["Michael", "S"] ]
],
[
[ ["Allen", "S"], ["Omer", "P"] ],
[ ["David E.", "R"], ["Richard X.", "P"] ]
]
]
arr = [ [ "Parker", "R" ], [ "Stew", "P" ] ]
puts rps_game_winner(arr).inspect
puts rps_tournament_winner(tourn_arr).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment