알고리즘

[BOJ] 20920 - 영단어 암기는 괴로워(JS)

로돌씨 2024. 10. 11. 17:54

 

풀이

let fs = require("fs");

let input = fs.readFileSync('예제.txt').toString().trim().split("\n");
const [N,M] = input.shift().split(" ").map(Number);

input = input.filter(a=> a.length >= M)

let map = new Map();

for(let i = 0; i < input.length ; i++){
    if(map.has(input[i])){
        map.set(input[i] , map.get(input[i]) + 1)
    }else {
        map.set(input[i] , 1 )
    }
}

map = [...map].sort(function(a,b){
    if(a[1]==b[1]){
        if(a[0].length == b[0].length){
            return a[0].localeCompare(b[0]);
        }else{
            return b[0].length - a[0].length
        }  
    }else{
        return b[1] - a[1]
    }
})
let answer = map.map(a=>a[0])
console.log(answer.join("\n"))

map을 이용해 빈도수를 구해준후 sort 기능을 이용해 만약 빈도수가 같을시에 단어의 길이까지 같다면 사전순으로 정렬하는 localeCompare를 이용해 사전순으로 정렬을 했고 , 그 뒤에 길이순 , 그뒤로 빈도순으로 정렬해 출력해주었다.