順列・組み合わせ のサンプルコード JS [permutation] [combination]
2019-06-307 min read
目次
概要
順列(permutation) と 組み合わせ(combination) のサンプルコードをJavaScriptで実装してみました。
順列 - permutation
サンプルコード
const permutation = (nums, k) => {
let ans = [];
if (nums.length < k) {
return [];
}
if (k === 1) {
for (let i = 0; i < nums.length; i++) {
ans[i] = [nums[i]];
}
} else {
for (let i = 0; i < nums.length; i++) {
let parts = nums.slice(0);
parts.splice(i, 1)[0];
let row = permutation(parts, k - 1);
for (let j = 0; j < row.length; j++) {
ans.push([nums[i]].concat(row[j]));
}
}
}
return ans;
};
Usage
let arr = permutation(['a', 'b', 'c'], 2);
console.log(JSON.stringify(arr));
// [["a","b"],["a","c"],["b","a"],["b","c"],["c","a"],["c","b"]]
組み合わせ - combination
サンプルコード
const combination = (nums, k) => {
let ans = [];
if (nums.length < k) {
return [];
}
if (k === 1) {
for (let i = 0; i < nums.length; i++) {
ans[i] = [nums[i]];
}
} else {
for (let i = 0; i < nums.length - k + 1; i++) {
let row = combination(nums.slice(i + 1), k - 1);
for (let j = 0; j < row.length; j++) {
ans.push([nums[i]].concat(row[j]));
}
}
}
return ans;
};
Usage
let arr = combination(['a', 'b', 'c'], 2);
console.log(JSON.stringify(arr));
// [["a","b"],["a","c"],["b","c"]]
Recommends
New Posts
Hot posts!
Date
Tags
(110)
(54)
(54)
(47)
(45)
(36)
(30)
(29)
(24)
(24)
(22)
(21)
(21)
(20)
(19)
(17)
(16)
(16)
(15)
(14)
(12)
(12)
(12)
(12)
(12)
(12)
(11)
(10)
(10)
(10)
(10)
(10)
(9)
(9)
(8)
(8)
(8)
(8)
(7)
(7)
(6)
(6)
(6)
(6)
(6)
(5)
(5)
(5)
(5)
(4)
Author