🧩 조합
- nCr, 서로다른 n개 중 r개 선택하되 순서를 안따짐
- 1,2,3 이랑 3,2,1 이랑 같은걸로 취급
- 코드
const getCombinations = function (arr, selectNumber) {
const results = [];
if (selectNumber === 1) return arr.map((value) => [value]);
arr.forEach((fixed, index, origin) => {
const rest = origin.slice(index + 1);
const combinations = getCombinations(rest, selectNumber - 1);
const attached = combinations.map((combination) => [fixed, ...combination]);
results.push(...attached);
});
return results;
}
const example = [1,2,3,4];
const result = getCombinations(example, 3);
console.log(result);
🧩 순열
- nPr, 서로다른 n개 중 r개 선택하되 순서를 따짐
- 1,2,3 이랑 3,2,1 이랑 다른걸로 취급
- 코드
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;
};
const example = [1,2,3,4];
const result = getPermutations(example, 3);
🧩 부분집합
- n개중 몇개를 뽑든 모든 경우의 수를 구함. 단, 순서를 안따짐
[1,2,3] 의 부분 집합
[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3]
let arr = [1,2,3,4];
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])
}
}
console.log(result);
🧩 완전탐색
- n개중 몇개를 뽑든 모든 경우의 수를 구함. 단, 순서를 따짐
[1,2,3] 의 완전탐색
[1],[2],[3],
[1,2],[2,1],[2,3],[3,2],[1,3],[3,1],
[1,2,3],[2,1,3],[2,3,1]...
let set = new Set();
numOfCase([1,7],'')
function numOfCase(arr,str) {
if(arr.length) {
for(let i = 0; i <arr.length; i++) {
let copy = [...arr];
copy.splice(i,1);
numOfCase(copy,str + arr[i])
}
}
if(str > 0) set.add(Number(str))
}
console.log(Array.from(set))
출처