1
1
/*
2
- * Problem Statement: Generate all distinct permutations of a string/ array (all permutations should be in sorted order);
2
+ * Problem Statement: Generate all distinct permutations of a an array (all permutations should be in sorted order);
3
3
*
4
4
* What is permutations?
5
- * - Permutation means possible arrangements in a set (here it is string/ array);
5
+ * - Permutation means possible arrangements in a set (here it is an array);
6
6
*
7
7
* Reference to know more about permutations:
8
8
* - https://www.britannica.com/science/permutation
@@ -17,17 +17,21 @@ const swap = (arr, i, j) => {
17
17
return newArray
18
18
}
19
19
20
- const permutations = ( arr , low , high ) => {
21
- if ( low === high ) {
22
- console . log ( arr . join ( ' ' ) )
23
- return
24
- }
25
- for ( let i = low ; i <= high ; i ++ ) {
26
- arr = swap ( arr , low , i )
27
- permutations ( arr , low + 1 , high )
20
+ const permutations = arr => {
21
+ let P = [ ]
22
+ const permute = ( arr , low , high ) => {
23
+ if ( low === high ) {
24
+ P . push ( [ ...arr ] )
25
+ // console.log(arr.join(' '))
26
+ return P
27
+ }
28
+ for ( let i = low ; i <= high ; i ++ ) {
29
+ arr = swap ( arr , low , i )
30
+ permute ( arr , low + 1 , high )
31
+ }
32
+ return P
28
33
}
34
+ return permute ( arr , 0 , arr . length - 1 )
29
35
}
30
36
31
- // Driver Code
32
- const input = [ 1 , 2 , 3 ]
33
- permutations ( input , 0 , input . length - 1 )
37
+ export { permutations }
0 commit comments