Permutation of an array that has smaller values from another array | Java program to find permutation of an array that has smaller values from another array ; Function to print required permutation ; Storing elements and indexes ; Sorting the Both Ap and Bp ; Filling the answer array ; Pair element of A and B ; Fill the remaining elements of answer ; Output required permutation ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void anyPermutation ( int A [ ] , int B [ ] , int n ) { ArrayList < int [ ] > Ap = new ArrayList < > ( ) ; ArrayList < int [ ] > Bp = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) Ap . add ( new int [ ] { A [ i ] , i } ) ; for ( int i = 0 ; i < n ; i ++ ) Bp . add ( new int [ ] { B [ i ] , i } ) ; Collections . sort ( Ap , ( x , y ) -> { if ( x [ 0 ] != y [ 0 ] ) return x [ 0 ] - y [ 0 ] ; return y [ 1 ] - y [ 1 ] ; } ) ; Collections . sort ( Bp , ( x , y ) -> { if ( x [ 0 ] != y [ 0 ] ) return x [ 0 ] - y [ 0 ] ; return y [ 1 ] - y [ 1 ] ; } ) ; int i = 0 , j = 0 ; int ans [ ] = new int [ n ] ; ArrayList < Integer > remain = new ArrayList < > ( ) ; while ( i < n && j < n ) { if ( Ap . get ( i ) [ 0 ] > Bp . get ( j ) [ 0 ] ) { ans [ Bp . get ( j ) [ 1 ] ] = Ap . get ( i ) [ 0 ] ; i ++ ; j ++ ; } else { remain . add ( i ) ; i ++ ; } } j = 0 ; for ( i = 0 ; i < n ; ++ i ) if ( ans [ i ] == 0 ) { ans [ i ] = Ap . get ( remain . get ( j ) ) [ 0 ] ; j ++ ; } for ( i = 0 ; i < n ; ++ i ) System . out . print ( ans [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int A [ ] = { 12 , 24 , 8 , 32 } ; int B [ ] = { 13 , 25 , 32 , 11 } ; int n = A . length ; anyPermutation ( A , B , n ) ; } }