forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeneratePermutations.js
More file actions
Latest commit
36 lines (31 loc) · 851 Bytes
/
Copy pathGeneratePermutations.js
File metadata and controls
36 lines (31 loc) · 851 Bytes
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
/*
* Problem Statement: Generate all distinct permutations of an array (all permutations should be in sorted order);
*
* What is permutations?
* - Permutation means possible arrangements in a set (here it is an array);
*
* Reference to know more about permutations:
* - https://www.britannica.com/science/permutation
*
*/
constswap=(arr,i,j)=>{
constnewArray=[...arr]
;[newArray[i],newArray[j]]=[newArray[j],newArray[i]]// Swapping elements ES6 way
returnnewArray
}
constpermutations=(arr)=>{
constP=[]
constpermute=(arr,low,high)=>{
if(low===high){
P.push([...arr])
returnP
}
for(leti=low;i<=high;i++){
arr=swap(arr,low,i)
permute(arr,low+1,high)
}
returnP
}
returnpermute(arr,0,arr.length-1)
}
export{permutations}