프로그래머스[Level 2] 메뉴 리뉴얼

bkboy·2022년 6월 29일
0

문제

링크

입출력 예

풀이

입출력 예제에 대한 설명을 보자.

AD가 세 번, CD가 세 번, ACD가 두번 ... 해당 주문에 대한 횟수가 짝지어서 설명이 되어있다. 여기서 객체나 map을 활용할 것을 눈치 채야한다.

알파벳 조합은 어떻게 해야할까. 말그대로 조합이다 combination으로 가능한 조합을 key로 하는 객체를 만들고 주문을 순회하며 가능한 것이 나왔을 때 값을 증가시켜준다.

값의 최대값을 구하고, 최대값과 같은 value를 지닌 key 값을 answer배열에 넣어준다.

function combination(arr, selectNumber) {
  const results = [];

  if (selectNumber === 1) {
    return arr.map((value) => [value]);
  }

  arr.forEach((fixed, index, origin) => {
    const rest = origin.slice(index + 1);
    const combinations = combination(rest, selectNumber - 1);
    const attached = combinations.map((combination) => [fixed, ...combination]);

    results.push(...attached);
  });

  return results;
}

function solution(orders, course) {
  const answer = [];

  for (let i = 0; i < course.length; i++) {
    const obj = {};

    orders.forEach((e) => {
      const combiArr = combination(e.split(""), course[i]);
      for (let x of combiArr) {
        const str = x.sort().join("");
        if (obj[str]) {
          obj[str] += 1;
        } else {
          obj[str] = 1;
        }
      }
    });

    const max = Math.max(...Object.values(obj));

    if (max >= 2) {
      for (const [key, value] of Object.entries(obj)) {
        if (value === max) {
          answer.push(key);
        }
      }
    }
  }

  return answer.sort();
}
profile
음악하는 개발자

0개의 댓글