순열, 조합

00_8_3·2022년 7월 27일
0

코테

목록 보기
1/2

중요 개념

  • fixer와 restArr을 이용.

순열

nPr
n! / (n-r)!
순서 상관 있다.
e.g ) [1,2,3] !== [3,2,1]

function permutation(arr, selectNum) {
  let result = [];
  if (selectNum === 1) return arr.map((v) => [v]);

  arr.forEach((v, idx, arr) => {
    const fixer = v;
    const restArr = arr.filter((_, index) => index !== idx);
    const permuationArr = permutation(restArr, selectNum - 1);
    const combineFixer = permuationArr.map((v) => [fixer, ...v]);
    result.push(...combineFixer);
  });
  return result;
}

중복순열

nπr
n의 r승
같은 문자 또는 수 중복 가능
e.g ) [1, 1, 1]

function permutation(arr, selectNum) {
  let result = [];
  if (selectNum === 1) return arr.map((v) => [v]);

  arr.forEach((v, idx, arr) => {
    const fixer = v;
    const restArr = arr; // 순열과 다른 부분
    const permuationArr = permutation(restArr, selectNum - 1);
    const combineFixer = permuationArr.map((v) => [fixer, ...v]);
    result.push(...combineFixer);
  });
  return result;
}

조합

nCr
n!/(n-r)!* r!
순서 상관 없다.
e.g ) [1, 2, 3] === [3, 2, 1][1, 2] == [2, 1]

function combination(arr, selectNum) {
  const result = [];
  if (selectNum === 1) return arr.map((v) => [v]);
  arr.forEach((v, idx, arr) => {
    const fixed = v;
    const restArr = arr.slice(idx+1);
    const combinationArr = combination(restArr, selectNum - 1);
    const combineFix = combinationArr.map((v) => [fixed, ...v]);
    result.push(...combineFix);
  });
  return result;
}

중복조합

nHr
(n+r-1)Cr
e.g ) 같은 문자 또는 수 중복 가능.

function combination(arr, selectNum) {
  const result = [];
  if (selectNum === 1) return arr.map((v) => [v]);
  arr.forEach((v, idx, arr) => {
    const fixed = v;
    const restArr = arr.slice(idx); // 조합과 다른부분
    const combinationArr = combination(restArr, selectNum - 1);
    const combineFix = combinationArr.map((v) => [fixed, ...v]);
    result.push(...combineFix);
  });
  return result;
}

0개의 댓글