1 minute read

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

찾아본 사항

조합 구현 함수

function combination(arr, num){
  const res = [];
  if(num === 1) return arr.map((v) => [v]);

  arr.forEach((v, idx, arr) => {
    const rest = arr.slice(idx+1);
    const combinations = combination(rest, num-1);
    const attach = combinations.map((combination) => [v, ...combination]);
    res.push(...attach);
  })
  return res;
}

배열에서 최대값 찾기

const maxValue = Math.max.apply(null, arr);

Math.max.apply(null, arr);

Math.max() 함수의 apply() 메소드를 호출하고 있습니다.

apply() 메소드의 첫번째 파라미터로는

Math.max() 함수 내부에서 사용할 this객체를 전달해야 하는데,

여기서는 따로 this객체를 지정해 줄 필요가 없으므로 null을 전달하였습니다.

apply() 메소드의 두번째 파라미터로는

Math.max() 함수로 전달할 파라미터를 배열 형태로 넣어주면 되는데,

Math.max() 함수에 전달할 파라미터 5개 (1, 2, 3, 4, 5)를 배열 형태로 만들어 전달(arr)하였습니다.

Math.max(), Math.min() 함수에 배열의 원소들을 풀어서 전달하기 위해

apply() 메소드를 활용한 것입니다.

출처: https://hianna.tistory.com/487 [어제 오늘 내일]

풀이 코드

function solution(orders, course) {
  var answer = [];
  let dict = {};
  for (let i of course) {
    let tempDict = {};

    for (let order of orders) {
      if (i > order.length) {
        continue;
      }
      let combis = combination(order.split(""), i);
      for (var x of combis) {
        let t = x.sort().join("");
        if (t in tempDict) tempDict[t] += 1;
        else {
          tempDict[t] = 1;
        }
        // console.log(t, tempDict[t]);
      }
    }
    dict[i] = tempDict;
  }
  for (const [dkey, dvalue] of Object.entries(dict)) {
    let maxCount = Math.max.apply(null, Object.values(dvalue));
    // console.log(dkey, maxCount);
    if (maxCount < 2) continue;
    for (const [key, value] of Object.entries(dvalue)) {
      if (value == maxCount) {
        // console.log(key, value);
        answer.push(key);
      }
    }
  }
  answer.sort();
  return answer;
}

function combination(arr, num) {
  const res = [];
  if (num === 1) return arr.map((v) => [v]);

  arr.forEach((v, idx, arr) => {
    const rest = arr.slice(idx + 1);
    const combinations = combination(rest, num - 1);
    const attach = combinations.map((combination) => [v, ...combination]);
    res.push(...attach);
  });
  return res;
}

var result = solution(["XYZ", "XWY", "WXA"], [2, 3, 4]);
console.log(result);

document.querySelector("#result").innerHTML = result;