문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
핵심 아이디어
- 장르별로 노래와 재생 횟수 분류:
- songsByGenre 객체에 각 장르별로 노래의 재생 횟수와 인덱스를 저장.
- genrePlayCount 객체에 각 장르의 총 재생 횟수를 저장.
- 장르 정렬:
- genrePlayCount를 기준으로 각 장르의 총 재생 횟수를 내림차순으로 정렬한 배열 sortedGenres를 생성.
- 장르별로 노래 정렬 및 상위 2개 선택:
- 각 장르에서 노래를 재생 횟수 기준으로 정렬하고, 재생 횟수가 동일하면 인덱스 순으로 정렬.
- 상위 2개의 노래를 선택해 answer 배열에 저장.
- 결과 반환:
- answer 배열을 평탄화(flat)해 최종적으로 베스트 앨범에 들어갈 노래들의 인덱스를 반환.
정답
function solution(genres, plays) {
const songsByGenre = {};
const genrePlayCount = {};
plays.forEach((play, index) => {
const genre = genres[index];
if (!songsByGenre[genre]) songsByGenre[genre] = [];
songsByGenre[genre].push({ play, index });
if (!genrePlayCount[genre]) genrePlayCount[genre] = 0;
genrePlayCount[genre] += play;
});
const sortedGenres = Object.keys(genrePlayCount).sort(
(a, b) => genrePlayCount[b] - genrePlayCount[a]
);
let answer = [];
sortedGenres.forEach(genre => {
const songs = songsByGenre[genre];
const sortedSongs = songs.sort((a, b) => {
if (a.play === b.play) {
return a.index - b.index;
}
return b.play - a.play;
});
answer.push(
Object.values(sortedSongs)
.slice(0, 2)
.map(data => data.index)
);
});
return answer.flat();
}