permutation
配列要素を並べ替えた全パターン組み合わせ
slice()とかナシでうまく書けないものか...?
require('array-permutation-simple')([1,2,3,4])で全パターン出てくる
shokai.icon作だったのか 増井俊之.icon
この下のやつをnpm化したん?
ほぼそうですshokai.icon
combinationとかも有るといいな 増井俊之.icon
code:permutation.js
// をほぼそのままコピーしてきたもの
(function() {
var generatePermutation = (pre, post, n, func) => {
var elem, i, rest
if(n > 0)
for (i=0; i < post.length; i++) {
rest = post.slice(0)
elem = rest.splice(i,1)
generatePermutation(pre.concat(elem), rest, n-1, func);
}
else
func(pre)
}
// extend Array.prototype
// e.g. 0, 1, 2.permutation(func, 2) => func(0,1), func(0,2), ... Array.prototype.permutation = function(func, n) {
if (n == null) n = this.length;
generatePermutation([], this, n, func)
}
})();
1, 2, 3.permutation((a) => alert(a), 2) できたshokai.icon
code:shokai-permutation.js
Array.prototype.permutation = function (callback) {
const permutationResult = []
function pickEach (result, arr) {
if (arr.length === 0) {
if (typeof callback === 'function') return callback(result)
return permutationResult.push(result)
}
for (let i = 0; i < arr.length; i++) {
let _arr = arr.concat()
let picked = _arr.splice(i, 1)
pickEach(result.concat(picked), _arr)
}
}
pickEach([], this)
return permutationResult
}
code:shokai-permutation.js
console.log(arr.permutation()) // 全リストを取得
arr.permutation(function (arr) { // 1つずつcallbackでも取れる
alert(arr)
})