rockPaperScissors.js (8kyu 23)
Codewars 알고리즘 풀이
Problem
- You have to return which player won.
- 가위바위보에서 승리한 플레이어를 반환한다.
- In case of a draw return Draw!.
- 비겼을 경우, Draw!를 반환한다.
Solution 01
function rockPaperScissors(p1, p2) {
if (p1 === p2) return 'Draw!';
if (p1 === 'rock' && p2 === 'scissors') {
return 'Player 1 won!';
} else if (p1 === 'paper' && p2 === 'rock') {
return 'Player 1 won!';
} else if (p1 === 'scissors' && p2 === 'paper') {
return 'Player 1 won!';
} else {
return 'Player 2 won!';
}
}
rockPaperScissors('rock', 'rock'); // Draw!
rockPaperScissors('scissors', 'rock'); // Player 2 won!
rockPaperScissors('paper', 'rock'); // Player 1 won!
rockPaperScissors('paper', 'paper'); // Draw!
Solution 02
function rockPaperScissors(p1, p2) {
if (p1 === p2) return 'Draw!';
const rules = {
rock: 'scissors',
paper: 'rock',
scissors: 'paper'
};
if (rules[p1] === p2) {
return 'Player 1 won!';
} else {
return 'Player 2 won!';
}
}
rockPaperScissors('rock', 'rock'); // Draw!
rockPaperScissors('scissors', 'rock'); // Player 2 won!
rockPaperScissors('paper', 'rock'); // Player 1 won!
rockPaperScissors('paper', 'paper'); // Draw!
Solution 03
function rockPaperScissors(p1, p2) {
const rules = {
rock: 'scissors',
paper: 'rock',
scissors: 'paper'
};
if (p1 === p2) {
return 'Draw!';
} else {
return 'Player ${rules[p1] === p2 ? 1 : 2} won!';
}
}
rockPaperScissors('rock', 'rock'); // Draw!
rockPaperScissors('scissors', 'rock'); // Player 2 won!
rockPaperScissors('paper', 'rock'); // Player 1 won!
rockPaperScissors('paper', 'paper'); // Draw!
Solution 04
function rockPaperScissors(p1, p2) {
if (p1 === p2) return 'Draw!';
return `Player ${/rockscissors|scissorspaper|paperrock/.test(p1 + p2) ? 1 : 2} won!`;
}
rockPaperScissors('rock', 'rock'); // Draw!
rockPaperScissors('scissors', 'rock'); // Player 2 won!
rockPaperScissors('paper', 'rock'); // Player 1 won!
rockPaperScissors('paper', 'paper'); // Draw!
정규표현식 (RegExp)
test()
: 대응되는 문자열이 있는지 검색하고, true/false를 반환한다.