Find n | Javascript program to print n - th permutation ; Utility for calculating factorial ; Function for nth permutation ; length of given string ; Count frequencies of all characters ; out string for output string ; Iterate till sum equals n ; We update both n and sum in this loop . ; Check for characters present in freq [ ] ; Remove character ; calculate sum after fixing a particular char ; if sum > n fix that char as present char and update sum and required nth after fixing char at that position ; if sum < n , add character back ; if sum == n means this char will provide its greatest permutation as nth permutation ; append string termination character and print result ; Driver code
let MAX_CHAR = 26 ; let MAX_FACT = 20 ; let fact = new Array ( MAX_FACT ) ; function precomputeFactorirals ( ) { fact [ 0 ] = 1 ; for ( let i = 1 ; i < MAX_FACT ; i ++ ) fact [ i ] = fact [ i - 1 ] * i ; } function nPermute ( str , n ) { precomputeFactorirals ( ) ; let len = str . length ; let freq = new Array ( MAX_CHAR ) ; for ( let i = 0 ; i < MAX_CHAR ; i ++ ) { freq [ i ] = 0 ; } for ( let i = 0 ; i < len ; i ++ ) freq [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; let out = " " ; let sum = 10 ; let k = 0 ; while ( sum >= n ) { for ( let i = 0 ; i < MAX_CHAR ; i ++ ) { if ( freq [ i ] == 0 ) continue ; freq [ i ] -- ; sum = 0 ; let xsum = fact [ len - 1 - k ] ; for ( let j = 0 ; j < MAX_CHAR ; j ++ ) xsum = Math . floor ( xsum / fact [ freq [ j ] ] ) ; sum += xsum ; if ( sum >= n ) { out += String . fromCharCode ( i + ' ' . charCodeAt ( 0 ) ) ; k ++ ; n -= ( sum - xsum ) ; break ; } if ( sum < n ) freq [ i ] ++ ; } } for ( let i = MAX_CHAR - 1 ; k < len && i >= 0 ; i -- ) if ( freq [ i ] != 0 ) { out += String . fromCharCode ( i + ' ' . charCodeAt ( 0 ) ) ; freq [ i ++ ] -- ; } document . write ( out ) ; } let n = 2 ; let str = " " ; nPermute ( str , n ) ;