개발 R.I.P.
9.05 Dev.Feedback(조합, 순열, 중복순열, 최대공약수, 최소공배수 Template)
편행
2021. 9. 5. 18:41
반응형
순열
순서가 상관이 있기때문에, index (중심이 되는 숫자의 index)를 제외한 다른 부분들을 다음 배열에 넣어줌
const getPermutations = function (arr, selectNumber) {
const results = [];
if (selectNumber === 1) return arr.map((e) => [e]);
arr.forEach((fixed, index) => {
const next = [...arr.slice(0, index), ...arr.slice(index+1)]
const permutations = getPermutations(next, selectNumber - 1);
const result = permutations.map((e) => [fixed, ...e]);
results.push(...result);
});
return results;
}
조합
순서가 상관이 없기때문에, 인덱스를 제외한 다른 부분을 다음 배열에 넣어줌
const getCombinations = function (arr, selectNumber) {
const results = [];
if (selectNumber === 1) return arr.map((e) => [e]);
arr.forEach((fixed, index) => {
const next = arr.slice(index + 1);
const combinations = getCombinations(next, selectNumber - 1);
const result = combinations.map((e) => [fixed, ...e]);
results.push(...result);
});
return results;
}
중복순열
모든 배열의 모든 요소가 겹쳐도 상관이 없기때문에 새로운 배열에 기존 배열 자체를 넣어줌
const getPermutations = function (arr, selectNumber) {
const results = [];
if (selectNumber === 1) return arr.map((e) => [e]);
arr.forEach((fixed, index) => {
const permutations = getPermutations(arr, selectNumber - 1);
const result = permutations.map((e) => [fixed, ...e]);
results.push(...result);
});
return results;
}
최대공약수
const gcd = (a, b) => a % b === 0 ? b : gcd(b, a % b);
최소공배수
const lcm = (a, b) => a * b / gcd(a, b);
반응형