Created
March 12, 2023 05:19
-
-
Save pjcodesjs/cec365d64f5e77ad3613a08192e32e0e to your computer and use it in GitHub Desktop.
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 generatePermutations(str) { | |
let result = []; | |
function permute(str, prefix = '') { | |
if (str.length === 0) { | |
result.push(prefix); | |
} else { | |
for (let i = 0; i < str.length; i++) { | |
let char = str[i]; | |
let remaining = str.slice(0, i) + str.slice(i + 1); | |
permute(remaining, prefix + char); | |
} | |
} | |
} | |
permute(str); | |
return result; | |
} | |
// To use this function, simply call it with a string: | |
let str = 'abc'; | |
let permutations = generatePermutations(str); | |
console.log(permutations); // prints ["abc", "acb", "bac", "bca", "cab", "cba"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment