I\'m in an introductory software development class, and my homework is to create a rock paper scissors program that takes two arguments (rock, paper), etc, and returns the arg t
I just think the simplest solution has to be something like:
@results = {
'rock/paper' => 'paper',
'rock/scissors' => 'rock',
'paper/scissors' => 'scissors',
'paper/rock' => 'paper',
'scissors/paper' => 'scissors',
'scissors/rock' => 'rock'
}
def winner p1, p2
@results["#{p1}/#{p2}"]
end
I don't know much about ruby, but I solved a problem like this long ago by using values for each one (eg, R = 1, P = 2, S=3).
Actually, I just googled after thinking about that and someone solved the problem in python using an array.
Here's one only using hashes:
RULES = {
:rock => {:rock => :draw, :paper => :paper, :scissors => :rock},
:paper => {:rock => :paper, :paper => :draw, :scissors => :scissors},
:scissors => {:rock => :rock, :paper => :scissors, :scissors => :draw}
}
def play(p1, p2)
RULES[p1][p2]
end
puts play(:rock, :paper) # :paper
puts play(:scissors, :rock) # :rock
puts play(:scissors, :scissors) # :draw
I very much doubt you've seen array/set intersections, so just for fun:
def who_wins(p1, p2)
win_moves = {"rock" => "paper", "paper" => "scissors", "scissors" => "rock"}
([p1, p2] & win_moves.values_at(p1, p2)).first
end
who_wins("rock", "paper") # "paper"
who_wins("scissors", "rock") # "rock"
who_wins("scissors", "scissors") # nil
A simple hash to the rescue:
def tell_me(a1, a2)
input = [a1 , a2].sort.join('_').to_sym
rules = { :paper_rock => "paper", :rock_scissor => "rock", :paper_scissor => "scissor"}
rules[input]
end
WINNAHS = [[:rock, :scissors], [:scissors, :paper], [:paper, :rock]]
def winner(p1, p2)
(WINNAHS.include?([p1,p2]) && p1) || (WINNAHS.include?([p2,p1]) && p2) || :tie
end
winner(:rock, :paper) #=> :paper
winner(:scissors, :paper) #=> :scissors
winner(:scissors, :scissors) #=> :tie