Lexicographic rank of a string | A utility function to find factorial of n ; A utility function to count smaller characters on right of arr [ low ] ; A function to find rank of a string in all permutations of characters ; count number of chars smaller than str [ i ] fron str [ i + 1 ] to str [ len - 1 ] ; Driver Code
< ? php function fact ( $ n ) { return ( $ n <= 1 ) ? 1 : $ n * fact ( $ n - 1 ) ; } function findSmallerInRight ( $ str , $ low , $ high ) { $ countRight = 0 ; for ( $ i = $ low + 1 ; $ i <= $ high ; ++ $ i ) if ( $ str [ $ i ] < $ str [ $ low ] ) ++ $ countRight ; return $ countRight ; } function findRank ( $ str ) { $ len = strlen ( $ str ) ; $ mul = fact ( $ len ) ; $ rank = 1 ; for ( $ i = 0 ; $ i < $ len ; ++ $ i ) { $ mul /= $ len - $ i ; $ countRight = findSmallerInRight ( $ str , $ i , $ len - 1 ) ; $ rank += $ countRight * $ mul ; } return $ rank ; } $ str = " string " ; echo findRank ( $ str ) ; ? >