-
Notifications
You must be signed in to change notification settings - Fork 230
/
Copy pathallPermutations.js
40 lines (31 loc) · 1.09 KB
/
allPermutations.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Write a recursive function for generating all permutations of an input string.
// Return them as a set.
const input = 'abc';
const expected = new Set([
'abc',
'acb',
'bac',
'bca',
'cab',
'cba'
]);
console.log(getPermutations(input));
function getPermutations(string) {
// Base case
if (string.length <= 1) {
return new Set([string]);
}
const allCharsExceptLast = string.slice(0, -1);
const lastChar = string[string.length - 1];
// Recursive call: get all possible permutations for all chars except last
const permutationsOfAllCharsExceptLast = getPermutations(allCharsExceptLast);
// Put the last char in all possible positions for each of the above permutations
const permutations = new Set();
permutationsOfAllCharsExceptLast.forEach(permutationOfAllCharsExceptLast => {
for (let position = 0; position <= allCharsExceptLast.length; position++) {
const permutation = permutationOfAllCharsExceptLast.slice(0, position) + lastChar + permutationOfAllCharsExceptLast.slice(position);
permutations.add(permutation);
}
});
return permutations;
}