Print distinct sorted permutations with duplicates allowed in input | Calculating factorial of a number ; Method to print the array ; Method to find total number of permutations ; Building HashMap to store frequencies of all characters . ; Traversing hashmap and finding duplicate elements . ; Start traversing from the end and find position ' i - 1' of the first character which is greater than its successor . ; Finding smallest character after ' i - 1' and greater than temp [ i - 1 ] ; Swapping the above found characters . ; Sort all digits from position next to ' i - 1' to end of the string . ; Print the String ; Sorting String ; Print first permutation ; Finding the total permutations ; Driver Code
function factorial ( n ) { let f = 1 ; for ( let i = 1 ; i <= n ; i ++ ) f = f * i ; return f ; } function print ( temp ) { for ( let i = 0 ; i < temp . length ; i ++ ) document . write ( temp [ i ] ) ; document . write ( " " ) ; } function calculateTotal ( temp , n ) { let f = factorial ( n ) ; let hm = new Map ( ) ; for ( let i = 0 ; i < temp . length ; i ++ ) { if ( hm . has ( temp [ i ] ) ) hm . set ( temp [ i ] , hm . get ( temp [ i ] ) + 1 ) ; else hm . set ( temp [ i ] , 1 ) ; } for ( let [ key , value ] of hm . entries ( ) ) { let x = value ; if ( x > 1 ) { let temp5 = factorial ( x ) ; f = Math . floor ( f / temp5 ) ; } } return f ; } function nextPermutation ( temp ) { let i ; for ( i = temp . length - 1 ; i > 0 ; i -- ) if ( temp [ i ] > temp [ i - 1 ] ) break ; let min = i ; let j , x = temp [ i - 1 ] ; for ( j = i + 1 ; j < temp . length ; j ++ ) if ( ( temp [ j ] < temp [ min ] ) && ( temp [ j ] > x ) ) min = j ; let temp_to_swap ; temp_to_swap = temp [ i - 1 ] ; temp [ i - 1 ] = temp [ min ] ; temp [ min ] = temp_to_swap ; temp = temp . slice ( 0 , i ) . sort ( ) . concat ( temp . slice ( i , temp . length ) ) ; print ( temp ) ; } function printAllPermutations ( s ) { let temp = s . split ( " " ) ; temp . sort ( ) ; print ( temp ) ; let total = calculateTotal ( temp , temp . length ) ; for ( let i = 1 ; i < total ; i ++ ) nextPermutation ( temp ) ; } let s = " " ; printAllPermutations ( s ) ;