팩토리얼, 순열, 조합

하태현·2021년 10월 30일
0

알고리즘

목록 보기
3/4
// 팩토리얼
const factorial = (n) => {
  if (n < 2) return 1;
  return n * factorial(n - 1);
};

// 순열
const permutaion = (n, r) => {
  return factorial(n) / factorial(n - r);
};

// 조합
const combination = (n, r) => {
  return permutaion(n, r) / factorial(r);
};

// 조합
function combination(arr, num) {
  let result = [];

  if (num < 2) return arr.map((e) => [e]);

  arr.forEach((e, i, array) => {
    const rest = [...array.slice(0, i), ...array.slice(i + 1)];
    const combinations = combination(rest, num - 1);
    const combiArr = combinations.map((x) => [e, ...x]);
    result.push(...combiArr);
  });
  return result;
}
profile
왜?를 생각하며 개발하기, 다양한 프로젝트를 경험하는 것 또한 중요하지만 내가 사용하는 기술이 어떤 배경과 이유에서 만들어진 건지, 코드를 작성할 때에도 이게 최선의 방법인지를 끊임없이 질문하고 고민하자. 이 과정은 앞으로 개발자로 커리어를 쌓아 나갈 때 중요한 발판이 될 것이다.

0개의 댓글