championshipPoints.js (8kyu 76)
Codewars 알고리즘 풀이
Problem
- Write a function that takes such list and counts the points of our team in the championship.
- 챔피언십에서 우리 팀의 점수를 계산한다.
Rules:
if x > y: 3 points
if x < y: 0 point
if x = y: 1 point
There are 10 matches in the championship
0 <= x <= 4
0 <= y <= 4
Solution 01
function championshipPoints(games) {
let result = 0;
for (let i = 0; i < games.length; i++) {
if (games[i][0] > games[i][2]) result += 3;
if (games[i][0] === games[i][2]) result += 1;
}
return result;
}
championshipPoints(['1:0', '2:0', '3:0', '4:0', '2:1', '3:1', '4:1', '3:2', '4:2', '4:3']); // 30
championshipPoints(['1:1', '2:2', '3:3', '4:4', '2:2', '3:3', '4:4', '3:3', '4:4', '4:4']); // 10
Solution 02
function championshipPoints(games) {
let result = 0;
games.map(i => {
i[0] > i[2] ? result += 3 : i[0] === i[2] ? result += 1 : result += 0;
});
return result;
}
championshipPoints(['1:0', '2:0', '3:0', '4:0', '2:1', '3:1', '4:1', '3:2', '4:2', '4:3']); // 30
championshipPoints(['1:1', '2:2', '3:3', '4:4', '2:2', '3:3', '4:4', '3:3', '4:4', '4:4']); // 10
map()
메소드배열 내 모든 element에 대해, 호출한 함수의 결과를 모아 새 배열로 반환한다.
Solution 03
function championshipPoints(games) {
let result = 0;
games.forEach(i => {
i[0] > i[2] ? result += 3 : i[0] === i[2] ? result += 1 : result += 0;
});
return result;
}
championshipPoints(['1:0', '2:0', '3:0', '4:0', '2:1', '3:1', '4:1', '3:2', '4:2', '4:3']); // 30
championshipPoints(['1:1', '2:2', '3:3', '4:4', '2:2', '3:3', '4:4', '3:3', '4:4', '4:4']); // 10
forEach()
메소드배열의 각 element에 대해, 제공된 함수를 차례로 한 번씩 호출한다.
Solution 04
function championshipPoints(games) {
return games.reduce((result, i) => {
return result += i[0] > i[2] ? 3 : i[0] === i[2] ? 1 : 0;
}, 0);
}
championshipPoints(['1:0', '2:0', '3:0', '4:0', '2:1', '3:1', '4:1', '3:2', '4:2', '4:3']); // 30
championshipPoints(['1:1', '2:2', '3:3', '4:4', '2:2', '3:3', '4:4', '3:3', '4:4', '4:4']); // 10
reduce()
메소드배열을 하나의 값으로 줄이고, 그 값을 반환한다.