|
1 | | -function permutations(str){ |
2 | | - |
| 1 | +const createPermutations = (str) => { |
3 | 2 | // convert string to array |
4 | | -let arr = str.split(''), |
| 3 | + const arr = str.split('') |
| 4 | + |
| 5 | + // get array length |
| 6 | + const strLen = arr.length |
| 7 | + // this will hold all the permutations |
| 8 | + const perms = [] |
| 9 | + let rest |
| 10 | + let picked |
| 11 | + let restPerms |
| 12 | + let next |
5 | 13 |
|
6 | | -// get array length |
7 | | - len = arr.length, |
8 | | -// this will hold all the permutations |
9 | | - perms = [], |
10 | | - rest, |
11 | | - picked, |
12 | | - restPerms, |
13 | | - next; |
14 | | - |
15 | | -// if len is zero, return the same string |
16 | | - if (len === 0) |
17 | | - return [str]; |
18 | | -// loop to the length to get all permutations |
19 | | - for (let i=0; i<len; i++) |
20 | | - { |
21 | | - rest = Object.create(arr); |
22 | | - picked = rest.splice(i, 1); |
| 14 | + // if strLen is zero, return the same string |
| 15 | + if (strLen === 0) { return [str] } |
| 16 | + // loop to the length to get all permutations |
| 17 | + for (let i = 0; i < strLen; i++) { |
| 18 | + rest = Object.create(arr) |
| 19 | + picked = rest.splice(i, 1) |
23 | 20 |
|
24 | | - restPerms = permutations(rest.join('')); |
| 21 | + restPerms = createPermutations(rest.join('')) |
25 | 22 |
|
26 | | - for (var j=0, jLen = restPerms.length; j< jLen; j++) |
27 | | - { |
28 | | - next = picked.concat(restPerms[j]); |
29 | | - perms.push(next.join('')); |
30 | | - } |
| 23 | + for (let j = 0, jLen = restPerms.length; j < jLen; j++) { |
| 24 | + next = picked.concat(restPerms[j]) |
| 25 | + perms.push(next.join('')) |
31 | 26 | } |
32 | | - return perms; |
| 27 | + } |
| 28 | + return perms |
33 | 29 | } |
34 | 30 |
|
35 | | -console.log(permutations('abc')) // should print ["abc", "acb", "bac", "bca", "cab", "cba"] |
36 | | - |
37 | | - |
| 31 | +console.log(createPermutations('abc')) // should print ["abc", "acb", "bac", "bca", "cab", "cba"] |
0 commit comments