Difference between lexicographical ranks of two given permutations | Function the print the difference between the lexicographical ranks ; Store the permutations in lexicographic order ; Initial permutation ; Initial variables ; Check permutation ; Initialize second permutation ; Check permutation ; Print difference ; Given array P [ ] ; Given array Q [ ] ; Given size ; Function call
def findDifference ( p , q , N ) : NEW_LINE INDENT A = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT A [ i ] = i + 1 NEW_LINE DEDENT IsCorrect = False NEW_LINE a , b = 1 , 1 NEW_LINE while True : NEW_LINE INDENT IsCorrect = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] != p [ i ] ) : NEW_LINE INDENT IsCorrect = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( IsCorrect ) : NEW_LINE INDENT break NEW_LINE DEDENT a += 1 NEW_LINE if ( not next_permutation ( A ) ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT A [ i ] = i + 1 NEW_LINE DEDENT while True : NEW_LINE INDENT IsCorrect = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] != q [ i ] ) : NEW_LINE INDENT IsCorrect = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( IsCorrect ) : NEW_LINE INDENT break NEW_LINE DEDENT b += 1 NEW_LINE if ( not next_permutation ( A ) ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( abs ( a - b ) ) NEW_LINE DEDENT def next_permutation ( p ) : NEW_LINE INDENT for a in range ( len ( p ) - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( p [ a ] < p [ a + 1 ] ) : NEW_LINE INDENT b = len ( p ) - 1 NEW_LINE while True : NEW_LINE INDENT if ( p [ b ] > p [ a ] ) : NEW_LINE INDENT t = p [ a ] NEW_LINE p [ a ] = p [ b ] NEW_LINE p [ b ] = t NEW_LINE a += 1 NEW_LINE b = len ( p ) - 1 NEW_LINE while a < b : NEW_LINE INDENT t = p [ a ] NEW_LINE p [ a ] = p [ b ] NEW_LINE p [ b ] = t NEW_LINE a += 1 NEW_LINE b -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT b -= 1 NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT p = [ 1 , 3 , 2 ] NEW_LINE q = [ 3 , 1 , 2 ] NEW_LINE n = len ( p ) NEW_LINE findDifference ( p , q , n ) NEW_LINE