Print k different sorted permutations of a given array | Javascript implementation of the approach ; Utility function to print the original indices of the elements of the array ; Function to print the required permutations ; To keep track of original indices ; Sort the array ; Count the number of swaps that can be made ; Cannot generate 3 permutations ; Print the first permutation ; Find an index to swap and create second permutation ; Print the last permutation ; Driver code ; Function call
var next_pos = 1 ; function printIndices ( n , a ) { for ( var i = 0 ; i < n ; i ++ ) document . write ( a [ i ] [ 1 ] + " " ) ; document . write ( " " ) ; } function printPermutations ( n , a , k ) { var arr = Array . from ( Array ( n ) , ( ) => Array ( 2 ) ) ; for ( var i = 0 ; i < n ; i ++ ) { arr [ i ] [ 0 ] = a [ i ] ; arr [ i ] [ 1 ] = i ; } arr . sort ( ) ; var count = 1 ; for ( var i = 1 ; i < n ; i ++ ) if ( arr [ i ] [ 0 ] == arr [ i - 1 ] [ 0 ] ) count ++ ; if ( count < k ) { document . write ( " " ) ; return ; } for ( var i = 0 ; i < k - 1 ; i ++ ) { printIndices ( n , arr ) ; for ( var j = next_pos ; j < n ; j ++ ) { if ( arr [ j ] [ 0 ] == arr [ j - 1 ] [ 0 ] ) { [ arr [ j ] , arr [ j - 1 ] ] = [ arr [ j - 1 ] , arr [ j ] ] ; next_pos = j + 1 ; break ; } } } printIndices ( n , arr ) ; } var a = [ 1 , 3 , 3 , 1 ] ; var n = a . length ; var k = 3 ; printPermutations ( n , a , k ) ;