Skip to content

Instantly share code, notes, and snippets.

@msaxena25
Created December 26, 2018 06:49
Show Gist options
  • Save msaxena25/1378302f497101c76797e9127ff05fff to your computer and use it in GitHub Desktop.
Save msaxena25/1378302f497101c76797e9127ff05fff to your computer and use it in GitHub Desktop.
JavaScript Create all possible Combination string from a given Input string : Example of Permutation
// First way
function swap (alphabets, index1, index2) {
var temp = alphabets[index1];
alphabets[index1] = alphabets[index2];
alphabets[index2] = temp;
return alphabets;
}
function permute (alphabets, startIndex, endIndex) {
if (startIndex === endIndex) {
console.log(alphabets.join(''));
} else {
var i;
for (i = startIndex; i <= endIndex; i++) {
swap(alphabets, startIndex, i);
permute(alphabets, startIndex + 1, endIndex);
swap(alphabets, i, startIndex); // backtrack
}
}
}
Output >
var alphabets = ['A','B','C'];
permute(alphabets, 0, alphabets.length -1 );
ABC
ACB
BAC
BCA
CBA
CAB
// Second way
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;
}
Ouput >
getAllPermutations("ABC")
 ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment