문제
https://school.programmers.co.kr/learn/courses/30/lessons/42579
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
map으로 장르 순위를 정하고~~
코드
function solution(genres, plays) {
let answer = [];
let music = new Map();
for(let i=0; i<genres.length; i++){ // 장르별 play 횟수 더하기
if(music.has(genres[i])) {
music.set(genres[i], music.get(genres[i])+plays[i]);
}
else {
music.set(genres[i], plays[i]);
}
}
while(music.size > 0) {
let songs = [];
let max = [...music.entries()].reduce((a,b)=> a[1]>b[1] ? a:b)[0]; // max 장르 구하기
genres.filter((genre, index) => {
if(genre === max) { // max 장르와 일치하면 songs 배열로 push
songs.push([plays[index], index]);
}
})
songs.sort((a,b) => { // songs 배열을 1. 많이 재생 2. 재생 횟수 같으면 index 낮은 순서로 정렬
if(a[0]===b[0]){
return a[1] - b[1];
} else {
return b[0] - a[0];
}
}).splice(2); // 2개씩 자르기
for(let num of songs){
answer.push(num[1]);
}
music.delete(max);
}
return answer;
}
다른 사람 풀이
function solution(genres, plays) {
const genreMap = new Map();
genres
.map((genre,index) => [genre, plays[index]])
.forEach(([genre, play], index) => {
const data = genreMap.get(genre) || { total: 0, songs: [] };
genreMap.set(genre, {
total: data.total + play,
songs: [...data.songs, { play, index }]
.sort((a, b) => b.play - a.play)
.slice(0, 2)
})
})
return [...genreMap.entries()]
.sort((a, b) => b[1].total - a[1].total)
.flatMap(item => item[1].songs)
.map(song => song.index)
}
Map은 아직 익숙하지 않은거 같다.....