Skip to content

Instantly share code, notes, and snippets.

@bioball
Last active December 25, 2015 07:29
Show Gist options
  • Save bioball/6939759 to your computer and use it in GitHub Desktop.
Save bioball/6939759 to your computer and use it in GitHub Desktop.
This is a Javascript function that takes an array, and returns all possible permutations of the same array.
function permute(arr){
return permutation(arr.sort());
}
function permutation(arr, result){
result = typeof result !== 'undefined' ? result : [];
result = result.concat([arr]);
//find index k
var k = null;
for( var i = 0; i < (arr.length-1); i++ ){
if (arr[i] < arr[i+1]){
var k = i;
}
}
//if k doesn't exist, we've reached the last permutation
if (k === null){
return result
}
//otherwise proceed with finding l, and call the function again
else {
//find index l
for ( var i = 0; i < arr.length; i++){
if (arr[i] > arr[k]){
var l = i;
}
}
//swap arr[k] and arr[l] and assign it to a new variable
var pArr = swap(arr, k, l);
//reverse the array after arr[k]
pArr = reverseafterk(pArr, k);
//call permutation on the new permutated arr
return permutation(pArr, result)
}
}
function swap(arr, a, b){
var i = arr[a];
arr[a] = arr[b];
arr[b] = i;
return arr;
}
function reverseafterk(arr, k){
var i = arr.splice(k+1);
return arr.concat(i.reverse());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment