알고리즘/프로그래머스

[프로그래머스][자바스크립트][Level2][카카오] 메뉴 리뉴얼

Benjamin_Choi 2022. 2. 14. 20:47

풀이

/**
 * 메뉴리뉴얼.js
 * https://programmers.co.kr/learn/courses/30/lessons/72411?language=javascript
 */

function solution(orders, course) {
    const answer = [];
    const orderMap = course.reduce((obj, num) => {
        obj[num] = { max: 0, orderComb: {}};
        return obj;
    }, {});
    
    course.forEach((num) => {
        orders.forEach((order) => {
            getCombinations(order.split(""), num).forEach((orderCombinated) => {
                const val = orderCombinated.sort().join("");
                if (!orderMap[num]["orderComb"][val]) {
                    orderMap[num]["orderComb"][val] = 1;
                } else {
                    orderMap[num]["orderComb"][val]++;
                }

                orderMap[num].max = Math.max(orderMap[num].max, orderMap[num]["orderComb"][val]);
            });
        });
    });

    Object.keys(orderMap).forEach((num) => {
        answer.push(...Object.keys(orderMap[num]["orderComb"]).filter((order) => orderMap[num].max > 1 && orderMap[num]["orderComb"][order] === orderMap[num].max));
    });

    return answer.sort();
}

const getCombinations = (array, selectNumber) => {
    const results = [];
    if(selectNumber === 1){
        return array.map((element) => [element]);
    }
    array.forEach((fixed, index, origin) => {
        const rest = origin.slice(index+1);
        const combinations = getCombinations(rest, selectNumber - 1);
        const attached = combinations.map((combination) => [fixed, ...combination]);
        results.push(...attached);
    });
    return results;
}

module.exports = solution;

 

orderMap 객체 schema는 아래와 같다. 

orderMap: { [key: number]: { max: number, orderComb: { [orderCombination: string]: number }} };

 

key는 course 숫자이며, max는 해당 course 갯수에서 가장 많이 나온 조합의 빈도수가 저장된다. orderComb는 order 조합을 저장한 객체다. 이렇게 orderMap 객체에 answer를 뽑아내는데에 필요한 모든 정보를 담을 수 있도록 정리했다.

 

우선 orderMap에 필요한 정보를 넣어준다. course와 orders를 순회하면서 getCombination 함수를 통해 뽑아낸 모든 조합의 경우들과 최대 빈도수 max를 orderMap에 넣어주면 된다. 

 

orderMap 정리가 끝나면 문제의 2가지 조건, 적어도 2명 이상에서 해당 조합을 뽑아낼 수 있어야한다는 조건과 같은 갯수의 조합 중 가장 많이 사용된 조합을 뽑아낸다는 조건으로 filter 해서 answer 배열에 담아주고 answer를 sort 해서 return 해주면 끝이다.