File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * Problem Statement: Generate all distinct permutations of a string/array (all permutations should be in sorted order);
3+ *
4+ * What is permutations?
5+ * - Permutation means possible arrangements in a set (here it is string/array);
6+ *
7+ * Reference to know more about permutations:
8+ * - https://www.britannica.com/science/permutation
9+ *
10+ */
11+
12+ const swap = ( arr , i , j ) => {
13+ const newArray = [ ...arr ] ;
14+
15+ [ newArray [ i ] , newArray [ j ] ] = [ newArray [ j ] , newArray [ i ] ] // Swapping elements ES6 way
16+
17+ return newArray
18+ }
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 )
28+ }
29+ }
30+
31+ // Driver Code
32+ const input = [ 1 , 2 , 3 ]
33+ permutations ( input , 0 , input . length - 1 )
You can’t perform that action at this time.
0 commit comments