Skip to content

Conversation

areumH
Copy link
Contributor

@areumH areumH commented Feb 5, 2025

🎯 문제 번호

42579

💡 풀이 설명

42579 베스트앨범

function getGenresCount(genres, plays) {
  const genresCount = {};

  genres.forEach((el, idx) => {
    genresCount[el] = (genresCount[el] || 0) + plays[idx][0];
  });

  return Object.entries(genresCount)
    .sort((a, b) => b[1] - a[1])
    .map((el) => el[0]);
}

function solution(genres, plays) {
  let answer = [];

  const indexPlays = plays.map((el, idx) => [el, idx]);
  const sortGenres = getGenresCount(genres, indexPlays);

  const genresIndex = sortGenres.map((el) => {
    return genres.map((genre, idx) => (el === genre ? idx : -1)).filter((idx) => idx !== -1);
  });

  for (let i = 0; i < genresIndex.length; i++) {
    const selected = genresIndex[i].map((idx) => indexPlays[idx]);
    answer.push(
      selected
        .sort((a, b) => b[0] - a[0])
        .slice(0, 2)
        .map((el) => el[1])
    );
  }

  return answer.flat();
}

간단한 듯 하면서도 은근 계산할 게 많아 약간의 노가다로 해결했다..💧먼저 가장 재생 수가 많은 순으로 장르를 리턴하는 함수를 선언해주었고, plays 배열은 map 함수를 통해 재생 횟수와 그 고유 번호(인덱스) 값을 가지도록 수정해주었다. 그리고 재생 수가 높은 장르 순으로 재생 수를 뽑아 selected 배열에 넣어주었다. selected 배열에 들어있는 각 요소는 [재생 수, 고유 번호]이므로 요소의 0번 인덱스를 사용해 재생 수가 높은 순으로 정렬해준 뒤, slice 함수를 사용해 길이를 2만큼 자르고 1번 인덱스 값(고유 번호)을 뽑아 answer 배열에 넣었다. 이 상태에서 answer은 2차원 배열이므로 flat 함수를 사용해 평탄화하여 답을 냈다!

✨ 사용한 알고리즘 (선택)

📗 참고 자료 (선택)

@areumH areumH requested a review from ccconac February 5, 2025 14:29
@areumH areumH self-assigned this Feb 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant