Skip to content

Instantly share code, notes, and snippets.

@masautt
Created September 6, 2019 04:21
Show Gist options
  • Save masautt/3033aea4a933ae26a3971263e71fc6dd to your computer and use it in GitHub Desktop.
Save masautt/3033aea4a933ae26a3971263e71fc6dd to your computer and use it in GitHub Desktop.
How to get all permutations of a string in JavaScript?
function getAllPermutations(string) {
var results = [];
if (string.length === 1) {
results.push(string);
return results;
}
for (var i = 0; i < string.length; i++) {
var firstChar = string[i];
var charsLeft = string.substring(0, i) + string.substring(i + 1);
var innerPermutations = getAllPermutations(charsLeft);
for (var j = 0; j < innerPermutations.length; j++) {
results.push(firstChar + innerPermutations[j]);
}
}
return results;
}
console.log(getAllPermutations("abc")); // --> [ 'abc', 'acb', 'bac', 'bca', 'cab', 'cba' ]
// https://initjs.org/all-permutations-of-a-set-f1be174c79f8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment