Created
May 24, 2018 02:29
-
-
Save reyou/d301003a04c6607339446ff19eaca289 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// https://stackoverflow.com/questions/7537791/understanding-recursion-to-generate-permutations/50382627#50382627 | |
let str = "ABC"; | |
permute(str, 0, str.length - 1, 0); | |
function permute(str, left, right, depth) { | |
if (left === right) { | |
console.log("PRINT:", str + "\n"); | |
} else { | |
for (let i = left; i <= right; i++) { | |
str = swap(str, left, i); | |
permute(str, left + 1, right, depth + 1); | |
str = swap(str, left, i); | |
} | |
} | |
} | |
function swap(str, left, right) { | |
let charArr = str.split(""); | |
let leftTemp = charArr[left]; | |
charArr[left] = charArr[right]; | |
charArr[right] = leftTemp; | |
return charArr.join(""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment