Skip to content

Commit 7b2c305

Browse files
authored
Merge pull request #403 from rubiin/master
Added createPermutation function
2 parents afb56cf + 90c4900 commit 7b2c305

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+
/*
2+
a permutation of a set is, loosely speaking, an arrangement of its members into a sequence or linear order, or if the set is already ordered, a rearrangement of its elements.
3+
The word "permutation" also refers to the act or process of changing the linear order of an ordered set
4+
More at : https://en.wikipedia.org/wiki/Permutation
5+
*/
6+
7+
const createPermutations = (str) => {
8+
// convert string to array
9+
const arr = str.split('')
10+
11+
// get array length
12+
const strLen = arr.length
13+
// this will hold all the permutations
14+
const perms = []
15+
let rest
16+
let picked
17+
let restPerms
18+
let next
19+
20+
// if strLen is zero, return the same string
21+
if (strLen === 0) { return [str] }
22+
// loop to the length to get all permutations
23+
for (let i = 0; i < strLen; i++) {
24+
rest = Object.create(arr)
25+
picked = rest.splice(i, 1)
26+
27+
restPerms = createPermutations(rest.join(''))
28+
29+
for (let j = 0, jLen = restPerms.length; j < jLen; j++) {
30+
next = picked.concat(restPerms[j])
31+
perms.push(next.join(''))
32+
}
33+
}
34+
return perms
35+
}
36+
37+
console.log(createPermutations('abc')) // should print ["abc", "acb", "bac", "bca", "cab", "cba"]

0 commit comments

Comments
 (0)