Last active
March 19, 2018 04:56
-
-
Save sghiassy/eab8327641211b1d258b6e04ec6f4ad6 to your computer and use it in GitHub Desktop.
A JavaScript (ES6) implementation of printing all Permutations of a String
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
// Print all permutations of a string in JavaScript (ES6) | |
// O(2^n) runtime | |
class StringSubsets { | |
constructor(str) { | |
this.str = str; | |
} | |
print() { | |
const map = new Map(); | |
for (let ch of this.str) { | |
map.set(ch, ((map.get(ch) || 0) + 1)); | |
} | |
this.recurse( | |
[...map.values()], | |
[...map.keys()], | |
new Array(this.str.length) | |
); | |
} | |
recurse(countMap, valuesMap, result, offset = 0, depth = 0) { | |
while (offset < result.length) { | |
if (countMap[offset] > 0) { | |
countMap[offset]--; | |
result[depth] = valuesMap[offset]; | |
console.log(result.join('')); | |
this.recurse(countMap, valuesMap, result, offset, depth + 1); | |
countMap[offset]++; | |
result[depth] = ''; | |
} | |
offset++; | |
} | |
} | |
} | |
const s = new StringSubsets("AABC"); | |
s.print(); | |
// OUTPUT | |
//A | |
//AA | |
//AAB | |
//AABC | |
//AAC | |
//AB | |
//ABC | |
//AC | |
//B | |
//BC | |
//C |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment