Created
September 22, 2017 18:44
-
-
Save fugufish/511c546df061cc54523b7970c954e203 to your computer and use it in GitHub Desktop.
permutations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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