728x90

문제


https://programmers.co.kr/learn/courses/30/lessons/72411

 

코딩테스트 연습 - 메뉴 리뉴얼

레스토랑을 운영하던 스카피는 코로나19로 인한 불경기를 극복하고자 메뉴를 새로 구성하려고 고민하고 있습니다. 기존에는 단품으로만 제공하던 메뉴를 조합해서 코스요리 형태로 재구성해서

programmers.co.kr

 

코드


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

  // 조합
  const getCombination = (arr, selectNumber) => {
    const result = [];
    if (selectNumber === 1) return arr.map((value) => [value]);

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

      result.push(...attached);
    });
    return result;
  };

  // 각 주문에 대해
  orders.map((order) => {
    const orderArr = order.split("").sort();

    for (let i = 2; i <= orderArr.length; i++) {
      // 원하는 조합구성 개수가 아닌 경우 넘어가기
      if (!course.includes(i)) continue;

      // 각 주문에 대한 모든 알파벳 조합 구하기
      const combs = getCombination(orderArr, i);
      combs.map((comb) => {
        const string = comb.join("");
        // 알파벳 조합에 대한 개수 구하기
        list[string] = list[string] ? list[string] + 1 : 1;
      });
    }
  });

  // 객체 list의 key, value를 배열로 구하기
  let listArr = Object.entries(list);
  course.map((amount) => {
    // 조합구성의 개수와 길이가 맞는 알파벳 중에서 2개이상인 것들은 후보로 담기
    const candidates = listArr.filter(
      (el) => el[0].length === amount && el[1] > 1
    );

    if (candidates.length > 0) {
      // 후보 중에서 가장 많이 주문된 조합을 정답에 담기
      let max = Math.max(...candidates.map((el) => el[1]));
      candidates.map((el) => {
        if (el[1] === max) answer.push(el[0]);
      });
    }
  });

  // 사전순으로 정렬하여 return
  return answer.sort();
}

 

후기


  • 조합과 객체, 배열의 특징을 잘 이용하여 풀 수 있는 문제였다.
  • 조합이나 순열이 약하거나 객체, 배열의 쓰임새에 대한 연습이 필요하면 풀기 좋은 문제인 것 같다. 
잘못된 내용이나 수정이 필요한 내용이 있으면 언제든 댓글 달아주세요 감사합니다 😀

+ Recent posts