티스토리 뷰

Hobby/Code

[ruby] Rock-Paper-Scissors class

생각많은 소심남 2014. 5. 19. 21:28

ESaaS 3번째 과제였다. standardError로 상속해서 따로 exception을 처리하는 부분과 여러개의 입력이 들어왔을 때 각 case에 대한 recursive call을 고려했어야 했다.


#!/usr/bin/env ruby

class RockPaperScissors
  class NoSuchStrategyError < StandardError ; end

  def self.winner(player1, player2)
    if not ["P","R","S"].include?(player1[1]) or not ["P","R","S"].include?(player2[1])
      raise NoSuchStrategyError, "Strategy must be one of R,P,S"
    end

    if player1[1] == "R" and player2[1] != "P"
      return player1
    elsif player1[1] == "P" and player2[1] != "S"
      return player1
    elsif player1[1] == "S" and player2[1] != "R"
      return player1
    else
      return player2
    end
  end

  def self.tournament_winner(tournament)
   if tournament[0][0].size != 2
     return winner(tournament[0], tournament[1]) 
   end
     winner(tournament_winner(tournament[0]), tournament_winner(tournament[1]))
  end
end


tournament_list = [
  [
    [ ["Armando", "P"], ["Dave", "S"] ],
    [ ["Richard", "R"], ["Michael", "S"] ],
  ],
  [
    [ ["Allen", "S"], ["Omer", "P"] ],
    [ ["David E.", "R"], ["Richard X.", "P"] ]
  ] 

]


'Hobby > Code' 카테고리의 다른 글

[C] fifteen game  (0) 2014.05.26
[C] vigenere cipher  (1) 2014.05.25
[C] Caesar Cipher  (1) 2014.05.25
[ruby] Very simple class for dessert  (0) 2014.05.19
[Ruby] Palindrome, dictionary, anagram  (0) 2014.05.18
[python] count inversion with mergesort  (0) 2014.05.18
[C] n squared matrix 덧셈  (0) 2014.05.14
댓글