Print k different sorted permutations of a given array | 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
def printIndices ( n , a ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] [ 1 ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " , ▁ end = " " ) NEW_LINE DEDENT def printPermutations ( n , a , k ) : NEW_LINE INDENT arr = [ [ 0 , 0 ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] [ 0 ] = a [ i ] NEW_LINE arr [ i ] [ 1 ] = i NEW_LINE DEDENT arr . sort ( reverse = False ) NEW_LINE count = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] [ 0 ] == arr [ i - 1 ] [ 0 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count < k ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE return NEW_LINE DEDENT next_pos = 1 NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT printIndices ( n , arr ) NEW_LINE for j in range ( next_pos , n ) : NEW_LINE INDENT if ( arr [ j ] [ 0 ] == arr [ j - 1 ] [ 0 ] ) : NEW_LINE INDENT temp = arr [ j ] NEW_LINE arr [ j ] = arr [ j - 1 ] NEW_LINE arr [ j - 1 ] = temp NEW_LINE next_pos = j + 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT printIndices ( n , arr ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 3 , 3 , 1 ] NEW_LINE n = len ( a ) NEW_LINE k = 3 NEW_LINE printPermutations ( n , a , k ) NEW_LINE DEDENT