Created
March 16, 2018 16:23
-
-
Save unreadable/285bde0d01e70ba3d0a50d44764b204c to your computer and use it in GitHub Desktop.
Permutation algorithm in javascript
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(str, i, j) { | |
let temp = str[i] | |
str = str.split(""); | |
str[i] = str[j]; | |
str[j] = temp; | |
return str.join(""); | |
} | |
function perm(str, startIndex, perms) { | |
for(let i = startIndex; i < str.length; i++) { | |
let temp = swap(str, startIndex, i); | |
if(startIndex != i) perms.push(temp); | |
perm(temp, startIndex + 1, perms); | |
} | |
return perms; | |
} | |
/* | |
let str = "abcd" | |
console.log(perm(str, 0, [str])); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment