I have written this snippet to find r-permutations of n, i.e. if I have an array of n=3 {0,1,2}, then r=2 permutations will be {{0, 1}, {0, 2}, {1, 0}, {1, 2}, {2, 0}, {2, 1}}. Can somebody review it and help me optimize / reduce its complexity (I don't want to use recursive function):
"_getAllPermutation": function(input, allPermutations, usedIndices, r) {
var index = 0,
usedIndex = null;
for (; index < input.length; index++) {
usedIndex = input.splice(index, 1)[0];
r--;
usedIndices.push(usedIndex);
if (input.length === 0 || r === 0) {
allPermutations.push(usedIndices.slice());
}
if (r > 0) {
this._getAllPermutation(input, allPermutations, usedIndices, r);
}
input.splice(index, 0, usedIndex);
r++;
usedIndices.pop();
}
}