rockPaperScissors.js (8kyu 40)

Codewars 알고리즘 풀이


Description

  • You have to return which player won.
    • 이긴 플레이어를 반환한다.
  • In case of a draw return ‘Draw!’.
    • 비긴 경우 ‘Draw!’를 반환한다.



Solution 01

function rockPaperScissors(p1, p2) {
  if (p1 === 'rock' && p2 === 'rock') return 'Draw!';
  if (p1 === 'rock' && p2 === 'paper') return 'Player 2 won!';
  if (p1 === 'rock' && p2 === 'scissors') return 'Player 1 won!';
  if (p1 === 'paper' && p2 === 'rock') return 'Player 1 won!';
  if (p1 === 'paper' && p2 === 'paper') return 'Draw!';
  if (p1 === 'paper' && p2 === 'scissors') return 'Player 2 won!';
  if (p1 === 'scissors' && p2 === 'rock') return 'Player 2 won!';
  if (p1 === 'scissors' && p2 === 'paper') return 'Player 1 won!';
  if (p1 === 'scissors' && p2 === 'scissors') return 'Draw!';
}

rockPaperScissors('rock', 'rock');      // Draw!
rockPaperScissors('rock', 'paper');     // Player 2 won!
rockPaperScissors('rock', 'scissors');  // Player 1 won!
rockPaperScissors('paper', 'rock');     // Player 1 won!


Solution 02

function rockPaperScissors(p1, p2) {
  if (p1 === p2) return 'Draw!';
  
  if (p1 === 'rock' && p2 === 'paper') return 'Player 2 won!';
  else if (p1 === 'paper' && p2 === 'scissors') return 'Player 2 won!';
  else if (p1 === 'scissors' && p2 === 'rock') return 'Player 2 won!';
  else return 'Player 1 won!';
}

rockPaperScissors('rock', 'rock');      // Draw!
rockPaperScissors('rock', 'paper');     // Player 2 won!
rockPaperScissors('rock', 'scissors');  // Player 1 won!
rockPaperScissors('paper', 'rock');     // Player 1 won!


Solution 03

function rockPaperScissors(p1, p2) {
  if (p1 === p2) return 'Draw!';
  
  const obj = {
    rock: 'scissors',
    paper: 'rock',
    scissors: 'paper'
  };
  
  if (p1 === obj[p2]) {
    return 'Player 2 won!';
  } else {
    return 'Player 1 won!';
  }
}

rockPaperScissors('rock', 'rock');      // Draw!
rockPaperScissors('rock', 'paper');     // Player 2 won!
rockPaperScissors('rock', 'scissors');  // Player 1 won!
rockPaperScissors('paper', 'rock');     // Player 1 won!


Solution 04

function rockPaperScissors(p1, p2) {
  const obj = {
    rock: 'scissors',
    paper: 'rock',
    scissors: 'paper'
  };
  
  if (p1 === p2) {
    return 'Draw!';
  } else {
    return 'Player ' + (p1 === obj[p2] ? 2 : 1) + ' won!';
  }
}

rockPaperScissors('rock', 'rock');      // Draw!
rockPaperScissors('rock', 'paper');     // Player 2 won!
rockPaperScissors('rock', 'scissors');  // Player 1 won!
rockPaperScissors('paper', 'rock');     // Player 1 won!


Solution 05

function rockPaperScissors(p1, p2) {
  if (p1 === p2) return 'Draw!';
  
  return `Player ${/rockscissors|paperrock|scissorspaper/.test(p1 + p2) ? 1 : 2} won!`;
}

rockPaperScissors('rock', 'rock');      // Draw!
rockPaperScissors('rock', 'paper');     // Player 2 won!
rockPaperScissors('rock', 'scissors');  // Player 1 won!
rockPaperScissors('paper', 'rock');     // Player 1 won!