function choose(arr, size) {
var allResult = [];
(function (arr, size, result) {
var arrLen = arr.length;
if (size > arrLen) {
return;
}
if (size == arrLen) {
allResult.push([].concat(result, arr))
} else {
for (var i = 0; i < arrLen; i++) {
var newResult = [].concat(result);
newResult.push(arr[i]);
if (size == 1) {
allResult.push(newResult);
} else {
var newArr = [].concat(arr);
newArr.splice(0, i + 1);
arguments.callee(newArr, size - 1, newResult);
}
}
}
})(arr, size, []);
return allResult;
}
ringa_lee
This is a permutation and combination implementation using black magic. The functions achieved are roughly:
choose([1, 2, 3], 1) gets [ [ 1 ], [ 2 ], [ 3 ] ]
choose([1, 2, 3], 2) gets [ [ 1, 2 ], [ 1, 3 ], [ 2, 3 ] ]
choose([1, 2, 3, 4], 3) gets [ [ 1, 2, 3 ], [ 1, 2, 4 ], [ 1, 3, 4 ], [ 2, 3, 4 ] ]
The inner anonymous function calls itself recursively through arguments.callee
. Each time it recursively calls itself, the size parameter is reduced by one. Each newResult is a [length is the total number of combinations, and each element is the current combination. ] is a two-dimensional array. When the length of each item in newResult reaches size, the recursion ends and the final result is returned.
Closure writing method prevents the internal parameters of the function from being affected by external factors.