Difference between lexicographical ranks of two given permutations | Java program for the above approach ; Function the print the difference between the lexicographical ranks ; Store the permutations in lexicographic order ; Intital permutation ; Initial variables ; Check permutation ; Initialize second permutation ; Check permutation ; Print difference ; Driver Code ; Given array P [ ] ; Given array Q [ ] ; Given size ; Function call
import java . util . * ; class GFG { static void findDifference ( int [ ] p , int [ ] q , int N ) { int [ ] A = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) A [ i ] = i + 1 ; boolean IsCorrect ; int a = 1 , b = 1 ; do { IsCorrect = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != p [ i ] ) { IsCorrect = false ; break ; } } if ( IsCorrect ) break ; a ++ ; } while ( next_permutation ( A ) ) ; for ( int i = 0 ; i < N ; i ++ ) A [ i ] = i + 1 ; do { IsCorrect = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != q [ i ] ) { IsCorrect = false ; break ; } } if ( IsCorrect ) break ; b ++ ; } while ( next_permutation ( A ) ) ; System . out . print ( Math . abs ( a - b ) + "NEW_LINE"); } static boolean next_permutation ( int [ ] p ) { for ( int a = p . length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { int t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } public static void main ( String [ ] args ) { int [ ] p = { 1 , 3 , 2 } ; int [ ] q = { 3 , 1 , 2 } ; int n = p . length ; findDifference ( p , q , n ) ; } }