본문 바로가기
Algorithm/프로그래머스

[해시] 베스트앨범

by seeker00 2021. 12. 16.

해시 | 베스트앨범

두어 달 전에 풀었던 코드
굉장히 조잡한 절차적 코드...!

import java.util.*;
import static java.util.stream.Collectors.*;
import java.util.LinkedList;

class Solution {
    public int[] solution(String[] genres, int[] plays) {
        int[] answer = {};

        Map<String, ArrayList> map = new HashMap<>();
        int len = genres.length;

        for (int i = 0; i < len; i++) {
            ArrayList<Integer> tmp = map.getOrDefault(genres[i], new ArrayList<Integer>()); //<장르, 장르별 인덱스>
            tmp.add(i);
            map.put(genres[i], tmp);
        }

        // 재생횟수 합에 따른 장르 정렬
        List<String> sorted = map.keySet().stream().sorted(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int sum1 = map.get(o1).stream().mapToInt(i -> plays[(int) i]).sum();
                int sum2 = (int) map.get(o2).stream().mapToInt(i -> plays[(int) i]).sum();
                return sum2 - sum1;
            }
        }).collect(toList());

        // 장르 내 음악 정렬 후 2개까지 자르기 
        List<Integer> list = new LinkedList();
        for (String key: sorted) {
            ArrayList<Integer> tmp = map.get(key);
            List<Integer> sortedList = tmp.stream()
                    .sorted(Comparator.comparingInt(a -> -plays[a]))
                    .limit(2)
                    .collect(toList());
            list.addAll(sortedList);
        }


        answer = new int[list.size()];
        int index = 0;
        for (Integer el : list) {
            answer[index] = (int) el;
            index++;
        }

        return answer;
    }
}



프로그래머스에서 발취한 다른 사람들의 코드...
깔끔하게 메소드를 분리했고, 객체, 스트림을 아주 잘 활용하는 것 같다.
flatMap과 map의 차이를 제대로 확인해보고 싶어서, stream debugger를 실행해보았는데 internal server error 가 떠서 그냥 sout으로 print로 확인해보았다.
flatMap을 거치면 요소 각각으로 쪼개어져서 스트림으로 반환된다.
(참고 : https://kchanguk.tistory.com/56)

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Solution {
  public class Music implements Comparable<Music>{

    private int played;
    private int id;
    private String genre;

    public Music(String genre, int played, int id) {
      this.genre = genre; 
      this.played = played;
      this.id = id;
    }

    @Override
    public int compareTo(Music other) {
      if(this.played == other.played) return this.id - other.id;
      return other.played - this.played;
    }

    public String getGenre() {return genre;}
  }

  public int[] solution(String[] genres, int[] plays) {
    return IntStream.range(0, genres.length)
    .mapToObj(i -> new Music(genres[i], plays[i], i))
    .collect(Collectors.groupingBy(Music::getGenre))
    .entrySet().stream()
    .sorted((a, b) -> sum(b.getValue()) - sum(a.getValue()))
    .flatMap(x->x.getValue().stream().sorted().limit(2))
    .mapToInt(x->x.id).toArray();
  }

  private int sum(List<Music> value) {
    int answer = 0;
    for (Music music : value) {
      answer+=music.played;
    }
    return answer;
  }
}

'Algorithm > 프로그래머스' 카테고리의 다른 글

2023 현대모비스 예선 - 상담원 인원  (0) 2023.09.29
[힙(Heap)] 더 맵게  (0) 2021.12.16
[깊이/너비 우선 탐색(DFS/BFS)] 타겟 넘버  (0) 2021.12.07
[해시] 위장  (0) 2021.09.24
[해시] 전화번호 목록  (0) 2021.09.16