points.js (8kyu 37)
Codewars 알고리즘 풀이
Description
- Our football team finished the championship.
- 우리 football 팀이 championship을 마쳤다.
- The result of each match look like ‘x:y’.
- 각 match 결과는 ‘x:y’이다.
- Results of all matches are recorded in the collection.
- 모든 match의 결과는 collection에 기록된다.
- Write a function that takes such collection and counts the points of our team in the championship.
- 우리 팀의 점수를 세는 함수를 작성한다.
Rules
x > y: 3 points
x = y: 1 point
x < y: 0 point
0 <= x <= 4
0 <= y <= 4
there are 10 matches
Solution 01
function points(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;
}
points(['0:1', '0:2', '0:3', '0:4', '1:2', '1:3', '1:4', '2:3', '2:4', '3:4']); // 0
points(['1:0', '2:0', '3:0', '4:4', '2:2', '3:3', '1:4', '2:3', '2:4', '3:4']); // 12
Solution 02
function points(games) {
let result = 0;
games.map(i => {
if (i[0] > i[2]) {
result += 3;
}
if (i[0] === i[2]) {
result += 1;
}
});
return result;
}
points(['0:1', '0:2', '0:3', '0:4', '1:2', '1:3', '1:4', '2:3', '2:4', '3:4']); // 0
points(['1:0', '2:0', '3:0', '4:4', '2:2', '3:3', '1:4', '2:3', '2:4', '3:4']); // 12
Solution 03
function points(games) {
return games.reduce((result, i) => {
return i[0] > i[2] ? (result += 3) : i[0] === i[2] ? (result += 1) : result;
}, 0);
}
points(['0:1', '0:2', '0:3', '0:4', '1:2', '1:3', '1:4', '2:3', '2:4', '3:4']); // 0
points(['1:0', '2:0', '3:0', '4:4', '2:2', '3:3', '1:4', '2:3', '2:4', '3:4']); // 12
Solution 04
function points(games) {
return games.map(i => i[0] - i[2]).filter(i => i >= 0).reduce((result, i) => result + (i > 0 ? 3 : 1), 0);
}
points(['0:1', '0:2', '0:3', '0:4', '1:2', '1:3', '1:4', '2:3', '2:4', '3:4']); // 0
points(['1:0', '2:0', '3:0', '4:4', '2:2', '3:3', '1:4', '2:3', '2:4', '3:4']); // 12