Created
February 17, 2019 07:43
-
-
Save Vigowebs/89ae66ef2b2ee0011240db608e7a5805 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 permut(string) { | |
if (string.length < 2) return string; // This is our break condition | |
var permutations = []; // This array will hold our permutations | |
for (var i=0; i<string.length; i++) { | |
var char = string[i]; | |
// Cause we don't want any duplicates: | |
if (string.indexOf(char) != i) // if char was used already | |
continue; // skip it this time | |
var remainingString = string.slice(0,i) + string.slice(i+1,string.length); | |
for (var subPermutation of permut(remainingString)) | |
permutations.push(char + subPermutation) | |
} | |
return permutations; | |
} | |
let permutations = permut('xyz'); | |
// ["xyz", "xzy", "yxz", "yzx", "zxy", "zyx"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment