조합, 순열, 부분집합 Javascript

미야옹·2021년 6월 30일
1

조합

const getCombination = (arr, n) => {
  const result = [];
  if(n === 1) return arr.map(e => [e]);
  arr.forEach((e, idx, origin) => {
    const rest = origin.slice(idx + 1);
    const combinations = getCombination(rest, n-1);
    const attached = combinations.map(combi => [e, ...combi]);
    result.push(...attached);
  });
  return result;
}

순열

const getPermutations= function (arr, selectNumber) {
  const results = [];
  if (selectNumber === 1) return arr.map((value) => [value]);

  arr.forEach((fixed, index, origin) => {
    const rest = [...origin.slice(0, index), ...origin.slice(index+1)]
    const permutations = getPermutations(rest, selectNumber - 1);
    const attached = permutations.map((permutation) => [fixed, ...permutation]);
    results.push(...attached);
  });

  return results;
};

부분집합

// 비트연산자 사용
let result = [];

for(let i = 1; i < (1 << arr.length); i++) {
  	result.push([]);
	for(let j = 0; j < arr.length; j++) {
    	if(i & (1 << j)) result[i-1].push(arr[j])
    }
}

0개의 댓글