Skip to content

Instantly share code, notes, and snippets.

@sghiassy
Last active March 19, 2018 04:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sghiassy/eab8327641211b1d258b6e04ec6f4ad6 to your computer and use it in GitHub Desktop.
Save sghiassy/eab8327641211b1d258b6e04ec6f4ad6 to your computer and use it in GitHub Desktop.
A JavaScript (ES6) implementation of printing all Permutations of a String
// 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