[ 프로그래머스 ] #72411 : 메뉴 리뉴얼 - JAVA

🔗 메뉴 리뉴얼

import java.util.*;
class Solution {

    private static HashMap<Integer, HashMap<String, Integer>> courseMap;

    public String[] solution(String[] orders, int[] course) {
        // 코스메뉴 : 최소 단품 메뉴 2 가지
        // 최소 2명 이상의 손님으로부터 주문된 단품메뉴 조합

        // orders : 손님들이 주문한 단품메뉴
        // course : 코스를 구성하는 단품 메뉴 개수

        // 해시맵 초기화
        courseMap = new HashMap<>();
        for(int i:course){
            courseMap.put(i,new HashMap<>());
        }

        // 코스를 배열로 만들고 오름차순 정렬해서 가능한 모든 메뉴 구성을 구함
        for(String order : orders){
            char [] orderArray = order.toCharArray();
            Arrays.sort(orderArray);
            combinations(0,orderArray,"");
        }

        ArrayList<String> answer=new ArrayList<>();

        // 모든 코스 후보에 대해서
        for(HashMap<String , Integer> count : courseMap.values()){
            count.values()
                .stream()
                // 가장 빈도수가 높은 코스를 찾음
                .max(Comparator.comparingInt(o->o))
                // 코스에 대한 메뉴 수가 가능할 때만
                .ifPresent(cnt -> count.entrySet()
                           .stream()
                           // 최소 2명의 손님으로부터 주문된 단품 메뉴 조합에 대해서만
                           .filter(entry -> cnt.equals(entry.getValue())&&
                                   cnt>1)
                           // 코스 메뉴만 answer 리스트에 추가 
                           .forEach(entry -> answer.add(entry.getKey())));         
        }
        Collections.sort(answer) ; // 오름차순으로 정렬
        return answer.toArray(new String[0]);
    }   

    // 조합 만들기 함수
    private static void combinations(int idx, char[] order , String result){
        // 코스 개수가 포함돼 있다면
        if(courseMap.containsKey(result.length())){
            // map을 가져오고
            HashMap<String, Integer> map=courseMap.get(result.length());
            // 조합 추가
            map.put(result, map.getOrDefault(result,0)+1);
        }

        // 끝까지 순회하면서 조합 계속 추가하기
        for(int i=idx;i<order.length;i++){
            combinations(i+1, order, result+order[i]);
        }
    }
}