Skip to content

Instantly share code, notes, and snippets.

@Vigowebs
Created February 17, 2019 07:43
Show Gist options
  • Save Vigowebs/89ae66ef2b2ee0011240db608e7a5805 to your computer and use it in GitHub Desktop.
Save Vigowebs/89ae66ef2b2ee0011240db608e7a5805 to your computer and use it in GitHub Desktop.
function permut(string) {
if (string.length < 2) return string; // This is our break condition
var permutations = []; // This array will hold our permutations
for (var i=0; i<string.length; i++) {
var char = string[i];
// Cause we don't want any duplicates:
if (string.indexOf(char) != i) // if char was used already
continue; // skip it this time
var remainingString = string.slice(0,i) + string.slice(i+1,string.length);
for (var subPermutation of permut(remainingString))
permutations.push(char + subPermutation)
}
return permutations;
}
let permutations = permut('xyz');
// ["xyz", "xzy", "yxz", "yzx", "zxy", "zyx"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment