Numbers of pairs from an array whose average is also present in the array | Java program for the above approach ; Function to count the number of pairs from the array having sum S ; Stores the total count of pairs whose sum is 2 * S ; Generate all possible pairs and check their sums ; If the sum is S , then increment the count ; Return the total count of pairs ; Function to count of pairs having whose average exists in the array ; Initialize the count ; Use set to remove duplicates ; Add elements in the set ; For every sum , count all possible pairs ; Return the total count ; Driver Code
import java . io . * ; import java . util . * ; class GFG { public static int getCountPairs ( int arr [ ] , int N , int S ) { int count = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { for ( int j = i + 1 ; j < arr . length ; j ++ ) { if ( ( arr [ i ] + arr [ j ] ) == S ) count ++ ; } } return count ; } public static int countPairs ( int arr [ ] , int N ) { int count = 0 ; HashSet < Integer > S = new HashSet < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) S . add ( arr [ i ] ) ; for ( int ele : S ) { int sum = 2 * ele ; count += getCountPairs ( arr , N , sum ) ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 5 , 1 , 3 , 5 } ; int N = arr . length ; System . out . print ( countPairs ( arr , N ) ) ; } }