text: Largest palindromic number by permuting digits | function to check if a number can be permuted to form a palindrome number ; counts the occurrence of number which is odd ; if occurrence is odd ; if number exceeds 1 ; function to print the largest palindromic number by permuting digits of a number ; string length ; map that marks the occurrence of a number ; check the possibility of a palindromic number ; string array that stores the largest permuted palindromic number ; pointer of front ; greedily start from 9 to 0 and place the greater number in front and odd in the middle ; if the occurrence of number is odd ; place one odd occurring number in the middle ; decrease the count ; place the rest of numbers greedily ; if all numbers occur even times , then place greedily ; place greedily at front ; 2 numbers are placed , so decrease the count ; increase placing position ; print the largest string thus formed ; driver code
code: function possibility ( m , length , s ) { var countodd = 0 ; for ( var i = 0 ; i < length ; i ++ ) { if ( m . get ( s . charCodeAt ( i ) - 48 ) & 1 ) countodd ++ ; if ( countodd > 1 ) return false ; } return true ; } function largestPalindrome ( s ) { var l = s . length ; var m = new Map ( ) ; for ( var i = 0 ; i < l ; i ++ ) { if ( m . has ( s . charCodeAt ( i ) - 48 ) ) m . set ( s . charCodeAt ( i ) - 48 , m . get ( s . charCodeAt ( i ) - 48 ) + 1 ) ; else m . set ( s . charCodeAt ( i ) - 48 , 1 ) ; } if ( possibility ( m , l , s ) == false ) { document . write ( " " ) ; return ; } var largest = new Array ( l ) ; var front = 0 ; for ( var i = 9 ; i >= 0 ; i -- ) { if ( m . has ( i ) & 1 ) { largest [ Math . floor ( l / 2 ) ] = String . fromCharCode ( i + 48 ) ; m . set ( i , m . get ( i ) - 1 ) ; while ( m . get ( i ) > 0 ) { largest [ front ] = String . fromCharCode ( i + 48 ) ; largest [ l - front - 1 ] = String . fromCharCode ( i + 48 ) ; m . set ( i , m . get ( i ) - 2 ) ; front ++ ; } } else { while ( m . get ( i ) > 0 ) { largest [ front ] = String . fromCharCode ( i + 48 ) ; largest [ l - front - 1 ] = String . fromCharCode ( i + 48 ) ; m . set ( i , m . get ( i ) - 2 ) ; front ++ ; } } } for ( var i = 0 ; i < l ; i ++ ) document . write ( largest [ i ] ) ; } var s = " " ; largestPalindrome ( s ) ;