Home > Article > Web Front-end > JavaScript implements exhaustive permutation (permutation) algorithm puzzle solution_javascript skills
Puzzle
Exhaustively list the arrangements of each element in an array
Strategy
Reduce and cure, recursion
JavaScript Solution
function getPermutation(arr) {
if (arr.length == 1) {
Return [arr];
}
var permutation = [];
for (var i=0; i
var arrClone = arr.slice(0);
arrClone.splice(i, 1);
var childPermutation = getPermutation(arrClone);
for (var j=0; j
}
Permutation = permutation.concat(childPermutation);
}
Return permutation;
}
var permutation = getPermutation(['a','b','c']);
console.dir(permutation);
Results