11/*
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);
33 *
44 * 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);
66 *
77 * Reference to know more about permutations:
88 * - https://www.britannica.com/science/permutation
@@ -17,17 +17,21 @@ const swap = (arr, i, j) => {
1717 return newArray
1818}
1919
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
2833 }
34+ return permute ( arr , 0 , arr . length - 1 )
2935}
3036
31- // Driver Code
32- const input = [ 1 , 2 , 3 ]
33- permutations ( input , 0 , input . length - 1 )
37+ export { permutations }
0 commit comments