Skip to content

Commit 2acf4c1

Browse files
authored
Create CreatePurmutations.js
1 parent 1671ea6 commit 2acf4c1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

String/CreatePurmutations.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
function permutations(str){
2+
3+
// convert string to array
4+
let arr = str.split(''),
5+
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);
23+
24+
restPerms = permutations(rest.join(''));
25+
26+
for (var j=0, jLen = restPerms.length; j< jLen; j++)
27+
{
28+
next = picked.concat(restPerms[j]);
29+
perms.push(next.join(''));
30+
}
31+
}
32+
return perms;
33+
}
34+
35+
console.log(permutations('abc')) // should print ["abc", "acb", "bac", "bca", "cab", "cba"]
36+
37+

0 commit comments

Comments
 (0)