[codewars] Rock Paper Scissors!

KJA·2022년 8월 24일
0

Description

Let's play! You have to return which player won! In case of a draw return Draw!.

Example

"scissors", "paper" --> "Player 1 won!"
"scissors", "rock" --> "Player 2 won!"
"paper", "paper" --> "Draw!"

문제 해결

const rps = (p1, p2) => {
  const rules = {
    rock : 1,
    scissors : 0,
    paper : -1,
  }
  const player1 = rules[p1];
  const player2 = rules[p2];
  const diff = player1 - player2;
  
  if([-2, 1].includes(diff)) return `Player 1 won!`;
  else if([2, -1].includes(diff)) return `Player 2 won!`;
  else return `Draw!`;
};

// player1 - player2
// -	가위	바위	보
// 가위	0	1	-1
// 바위	-1	0	-2
// 보	1	2	0

다른 풀이

const rps = (p1, p2) => {
  if (p1 === p2) return "Draw!";
  var rules = {rock: "scissors", paper: "rock", scissors: "paper"};
  if (p2 === rules[p1]) {
    return "Player 1 won!";
  }
  else {
    return "Player 2 won!";
  }
};

0개의 댓글