백준 올림픽 문제를 풀다가 Map 객체를 이용해서 문제를 풀었는데, 값이 같을때 등수를 어떤식으로 매겨야하는 것인지 정리 해둘 필요가 있었다.
등수는 자기보다 높은 점수를 가진 나라의 갯수 + 1 이다.
1과 5가 1등, value가 같은 2와 4는 각각 3등, 6이 5등, 3이 제일 낮으니 총 key 갯수에서 가장 낮은 6등이라면 ?
1 => 1
5 => 1
2 => 3
4 => 3
6 => 5
3 => 6
이런식으로 값이 나와야한다.
const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().trim().split("\n");
let nAndK = input.shift().split(' ').map(str => Number(str));
let [N, K] = [nAndK[0], nAndK[1]];
let countryAndMedal = input.map(arr => arr.split(' ').map(str => Number(str))).sort((a, b) => a[0] - b[0]);
let answer = 0;
let countryMap = new Map();
for(let i = 0; i < countryAndMedal.length; i++){
let sum = 0;
for(let j = 1; j < countryAndMedal[i].length; j++){
if(j === 1){
sum += countryAndMedal[i][j] * 3;
} else if( j === 2){
sum += countryAndMedal[i][j] * 2;
} else if( j === 3){
sum += countryAndMedal[i][j] * 1;
}
}
countryMap.set(i+1, sum);
}
let countryMapArr = [...countryMap].sort((a, b) => {
if(a[1] === b[1]){
return a[0] - b[0]
} else{
return b[1] - a[1]
}
});
// 등수를 담을 Map
let rankMap = new Map();
// sort해준후, value가 높은 순부터 반복문을 돌면서 다시 거꾸로 위로 반복문을 돈다.
// 본인보다 value가 높은 key가 존재한다면 rank를 1씩 더해주어서 등수를 업데이트한다.
for(let i = 0; i < countryMapArr.length; i++){
let rank = 1;
let memCount = countryMapArr[i][1];
for(let j = i-1; j >= 0; j--){
if(memCount < countryMapArr[j][1]){
rank++;
}
}
rankMap.set(countryMapArr[i][0], rank);
}
rankMap.forEach((value, key) => key === K ? answer = value : undefined);
console.log(answer);