Numbers of pairs from an array whose average is also present in the array | Function to count the total count of pairs having sum S ; Store the total count of all elements in map mp ; Initialize value to 0 , if key not found ; Stores the total count of total pairs ; Iterate through each element and increment the count ; If the value ( S - arr [ i ] ) exists in the map hm ; Update the twice count ; Return the half of twice_count ; Function to count of pairs having whose average exists in the array ; Stores the total count of pairs ; Use set to remove duplicates ; Insert all the element in the set S ; For every sum find the getCountPairs ; Return the total count of pairs ; Driver Code
function getCountPairs ( arr , N , S ) { let mp = new Map ( ) ; for ( let i = 0 ; i < N ; i ++ ) { if ( ! mp . has ( arr [ i ] ) ) mp . set ( arr [ i ] , 0 ) ; mp . set ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } let twice_count = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( mp . get ( S - arr [ i ] ) != null ) { twice_count += mp . get ( S - arr [ i ] ) ; } if ( S - arr [ i ] == arr [ i ] ) twice_count -- ; } return Math . floor ( twice_count / 2 ) ; } function countPairs ( arr , N ) { let count = 0 ; let S = new Set ( ) ; for ( let i = 0 ; i < N ; i ++ ) S . add ( arr [ i ] ) ; for ( let ele of S . values ( ) ) { let sum = 2 * ele ; count += getCountPairs ( arr , N , sum ) ; } return count ; } let N = 6 ; let arr = [ 4 , 2 , 5 , 1 , 3 , 5 ] ; document . write ( countPairs ( arr , N ) ) ;