Skip to content

Instantly share code, notes, and snippets.

@pjcodesjs
Created March 12, 2023 05:19
Show Gist options
  • Save pjcodesjs/cec365d64f5e77ad3613a08192e32e0e to your computer and use it in GitHub Desktop.
Save pjcodesjs/cec365d64f5e77ad3613a08192e32e0e to your computer and use it in GitHub Desktop.
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