HW impossibility?: “Create a rock paper scissors program in ruby WITHOUT using conditionals”

后端 未结 8 1881
我寻月下人不归
我寻月下人不归 2021-02-14 16:50

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

相关标签:
8条回答
  • 2021-02-14 17:25

    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
    
    0 讨论(0)
  • 2021-02-14 17:31

    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.

    0 讨论(0)
  • 2021-02-14 17:34

    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
    
    0 讨论(0)
  • 2021-02-14 17:35

    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
    
    0 讨论(0)
  • 2021-02-14 17:44

    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
    
    0 讨论(0)
  • 2021-02-14 17:48
    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 
    
    0 讨论(0)
提交回复
热议问题