Count of pairs in an Array with same number of set bits | Function to return the count of Pairs ; Get the maximum element ; Array to store count of bits of all elements upto maxm ; Store the set bits for powers of 2 ; Compute the set bits for the remaining elements ; Store the frequency of respective counts of set bits ; Driver Code
function countPairs ( arr , N ) { var maxm = arr . reduce ( ( a , b ) => Math . max ( a , b ) ) ; var i , k ; var bitscount = Array ( maxm + 1 ) . fill ( 0 ) ; for ( i = 1 ; i <= maxm ; i *= 2 ) bitscount [ i ] = 1 ; for ( i = 1 ; i <= maxm ; i ++ ) { if ( bitscount [ i ] == 1 ) k = i ; if ( bitscount [ i ] == 0 ) { bitscount [ i ] = bitscount [ k ] + bitscount [ i - k ] ; } } var setbits = new Map ( ) ; for ( var i = 0 ; i < N ; i ++ ) { if ( setbits . has ( bitscount [ arr [ i ] ] ) ) setbits . set ( bitscount [ arr [ i ] ] , setbits . get ( bitscount [ arr [ i ] ] ) + 1 ) else setbits . set ( bitscount [ arr [ i ] ] , 1 ) } var ans = 0 ; setbits . forEach ( ( value , key ) => { ans += value * ( value - 1 ) / 2 ; } ) ; return ans ; } var N = 12 ; var arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 ] ; document . write ( countPairs ( arr , N ) ) ;