프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
/**
 * num개로 이루어진 가능한 모든 조합을 반환하는 함수
 *
 * @param {string[]} order
 * @param {number[]} num 조합을 이룰 order의 개수
 * @returns
 */
function getCombination(order, num) {
  let result = [];
  if (num === 1) return order.map((el) => [el]);
  order.forEach((fixed, idx) => {
    let rest = order.slice(idx + 1);
    let combinationList = getCombination(rest, num - 1);
    let attached = combinationList.map((el) => [fixed, ...el]);
    result.push(...attached);
  });
  return result.map((el) => el.sort().join(''));
}
function solution(orders, course) {
  let result = [];
  let combinationCount = {};
  orders.forEach((order) => {
    course.forEach((num) => {
      getCombination(order.split(''), num).forEach((el) => {
        combinationCount[el] = combinationCount[el] + 1 || 1;
      });
    });
  });
  course.forEach((num) => {
    let maxOrderCount = 0;
    for (const KEY in combinationCount) {
      if (num !== KEY.length) continue;
      if (combinationCount[KEY] > maxOrderCount) {
        maxOrderCount = combinationCount[KEY];
      }
    }
    for (const KEY in combinationCount) {
      if (KEY.length !== num) continue;
      if (combinationCount[KEY] < 2) continue;
      if (combinationCount[KEY] === maxOrderCount) {
        result.push(KEY);
      }
    }
  });
  console.log(combinationCount);
  result = result.sort();
  return result;
}
const orders = ['XYZ', 'XWY', 'WXA'];
const course = [2, 3, 4];
const answer = solution(orders, course);
console.log(answer);
조합을 구현하는것에 익숙하지 않다면 Level 2에서 어려웠던 문제였던 것 같다. (내가 그랬다...)
조합만 구현할 줄 안다면 나머진 구현파트라 크게 어렵진 않았다.
course에 담긴 숫자들이 의미하는것은 조합에 들어간 메뉴의 개수인데, 가능한 모든 조합을 객체에 저장한다.
그리고 그 조합들이 몇번 나왔는지 count를 value값으로 가진다.
그 후 문제에서 원하는 개수와 같은 value값을 가진 key값(조합)을 찾아내서 그 중 최댓값을 result 배열에 넣어주면 된다.
'PS > Programmers' 카테고리의 다른 글
| Programmers / Level 3 / 줄 서는 방법 / JS (1) | 2023.01.21 | 
|---|---|
| Programmers / Level 2 / 2 x n 타일링 / JS (0) | 2023.01.19 | 
| Programmers / Level 2 / 피로도 / JS (0) | 2023.01.14 | 
| Programmers / Level 0 / 다음에 올 숫자 / JS (0) | 2023.01.11 |