Created
September 6, 2019 04:21
-
-
Save masautt/3033aea4a933ae26a3971263e71fc6dd to your computer and use it in GitHub Desktop.
How to get all permutations of a string in JavaScript?
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
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