Skip to content

Instantly share code, notes, and snippets.

@fugufish
Created September 22, 2017 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fugufish/511c546df061cc54523b7970c954e203 to your computer and use it in GitHub Desktop.
Save fugufish/511c546df061cc54523b7970c954e203 to your computer and use it in GitHub Desktop.
permutations
function swap(array, left, right) {
let c1 = array[left];
let c2 = array[right];
array[left] = c2;
array[right] = c1;
return array
}
function permute(string, index=0) {
// we have finished permuting the string, return the string so it can be added to the list
if (string.length == index+1) {
return console.log(string)
}
let buffer = string.split('') // easier to work with an array
// starting with the current index position loop through and swap characters
for (let i = index; i < buffer.length; i++) {
buffer = swap(buffer, index, i)
permute(buffer.join(''), index+1)
}
}
permute("asdf")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment