[Algorithm] 해쉬: 베스트 앨범 (프로그래머스 Lv3)

task11·2022년 4월 21일
0

알고리즘뽀개기

목록 보기
10/20
post-thumbnail

💡 알고리즘 Hash Map으로 풀이, 프로그래머스 3단계

문제 🛫


베스트 앨범

문제 참조 : https://programmers.co.kr/learn/courses/30/lessons/42579

스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다.

  • 속한 노래가 많이 재생된 장르를 먼저 수록합니다.
  • 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
  • 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.

노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 plays가 주어질 때, 베스트 앨범에 들어갈 노래의 고유 번호를 순서대로 return 하도록 solution 함수를 완성하세요.

제한사항
genres[i]는 고유번호가 i인 노래의 장르입니다.
plays[i]는 고유번호가 i인 노래가 재생된 횟수입니다.
genres와 plays의 길이는 같으며, 이는 1 이상 10,000 이하입니다.
장르 종류는 100개 미만입니다.
장르에 속한 곡이 하나라면, 하나의 곡만 선택합니다.
모든 장르는 재생된 횟수가 다릅니다.

TestCase
genres plays return
["classic", "pop", "classic", "classic", "pop"][500, 600, 150, 800, 2500] [4, 1, 3, 0]

분석

해쉬 맵을 이용하여 풀 수 있는 문제이다. (고차함수 이해도가 많이 필요함)

1) 같은 장르끼리 묶는다.
2) 묶인 노래들을 재생 횟수로 정렬.
3) 노래를 2개까지 잘라야함.

풀이 📖


Solution

function solution(genres, plays) {
  const hashMap = new Map();

  genres
    .map((genres, index) => [genres, plays[index]])
    .forEach(([genres, play], index) => {
      const data = hashMap.get(genres) || { total: 0, songs: [] };
      hashMap.set(genres, {
        total: data.total + play,
        songs: [...data.songs, { play, index }]
          .sort((a, b) => b.play - a.play)
          .slice(0, 2)
      });
    });

  return [...hashMap.entries()]
    .sort((a, b) => b[1].total - a[1].total)
    .flatMap(item => item[1].songs)
    .map(song => song.index);
}

//TC
console.log(solution(["classic", "pop", "classic", "classic", "pop"], [500, 600, 150, 800, 2500]));

분석(line by line)

코드 line마다 뜯어보기

  • part1: hashMap에 데이터 가공
const genres = ["classic", "pop", "classic", "classic", "pop"];
const plays = [500, 600, 150, 800, 2500];

const hashMap = new Map();

genres
    .map((genres, index) => [genres, plays[index]])
    .forEach(([genres, play], index) => {
      const data = hashMap.get(genres) || { total: 0, songs: [] };
      hashMap.set(genres, {
        total: data.total + play,
        songs: [...data.songs, { play, index }]
          .sort((a, b) => b.play - a.play)
          .slice(0, 2)
      });
    });
  • Input & Init
const genres = ["classic", "pop", "classic", "classic", "pop"];
const plays = [500, 600, 150, 800, 2500];

const hashMap = new Map(); // 결과를 담을 Map
  • 중첩 고차함수
genres.map((genres, index) => [genres, plays[index]])
// [
//  [ 'classic', 500 ],
//  [ 'pop', 600 ],
//  [ 'classic', 150 ],
//  [ 'classic', 800 ],
//  [ 'pop', 2500 ]
//]
.forEach(([genres, play], index) => {
  	  // 첫 data가 없으면 {total: 0, songs: []}로 초기화 한다.
      const data = hashMap.get(genres) || { total: 0, songs: [] };
	  // hashMap에 데이터를 set하여 data 변수에 넣는다.
  	  // 첫 번째 인자는 장르
  	  // 두 번째 인자는 {"total": data의 total + play수, "songs": [노래들, {play수, index순서}]를 play 수로 내림차순 정렬 및 2 곡 선정}
      hashMap.set(genres, {
        total: data.total + play,
        songs: [...data.songs, { play, index }]
          .sort((a, b) => b.play - a.play)
          .slice(0, 2)
      });
    });

//가공 후 HashMap
//Map(2) {
//  'classic' => { total: 1450, songs: [ [Object], [Object] ] },
//  'pop' => { total: 3100, songs: [ [Object], [Object] ] }
//}
  • return 값(hashMap의 인덱스만 출력)
// [hashMap의 entries(객체의 key, value를 배열로 감싸 전달)를 speard] 를 total로 내림차순 정렬,
// flatMap을 사용해서 최상위 배열 걷어낸 상태로 배열로 반환, map으로 index만 반환
return [...hashMap.entries()]
    .sort((a, b) => b[1].total - a[1].total)
    .flatMap(item => item[1].songs)
    .map(song => song.index);

Review 💡

머릿속으로는 구현을 했는데, 고차함수 활용능력이 부족해서 너무 어려웠던 문제이다.

  • hash Map 자료구조의 메서드를 이해해야한다.(entries 등)
  • 고차함수(map, forEach, flatMap) 활용하는 법을 이해해야한다.
  • 구조분해할당, spread문법을 활용해야한다.
  • hash 형태의 자료구조를 접근하는 방법에 대해 고민해야한다.

0개의 댓글