Count quadruples from four sorted arrays whose sum is equal to a given value x | Java implementation to count quadruples from four sorted arrays whose sum is equal to a given value x ; count pairs from the two sorted array whose sum is equal to the given ' value ' ; traverse ' arr1 [ ] ' from left to right traverse ' arr2 [ ] ' from right to left ; if the ' sum ' is equal to ' value ' , then increment ' l ' , decrement ' r ' and increment ' count ' ; if the ' sum ' is greater than ' value ' , then decrement r ; else increment l ; required count of pairs ; function to count all quadruples from four sorted arrays whose sum is equal to a given value x ; generate all pairs from arr1 [ ] and arr2 [ ] ; calculate the sum of elements in the pair so generated ; count pairs in the 3 rd and 4 th array having value ' x - p _ sum ' and then accumulate it to ' count ' ; required count of quadruples ; Driver program to test above ; four sorted arrays each of size ' n '
class GFG { static int countPairs ( int arr1 [ ] , int arr2 [ ] , int n , int value ) { int count = 0 ; int l = 0 , r = n - 1 ; while ( l < n & r >= 0 ) { int sum = arr1 [ l ] + arr2 [ r ] ; if ( sum == value ) { l ++ ; r -- ; count ++ ; } else if ( sum > value ) r -- ; else l ++ ; } return count ; } static int countQuadruples ( int arr1 [ ] , int arr2 [ ] , int arr3 [ ] , int arr4 [ ] , int n , int x ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) { int p_sum = arr1 [ i ] + arr2 [ j ] ; count += countPairs ( arr3 , arr4 , n , x - p_sum ) ; } return count ; } static public void main ( String [ ] args ) { int arr1 [ ] = { 1 , 4 , 5 , 6 } ; int arr2 [ ] = { 2 , 3 , 7 , 8 } ; int arr3 [ ] = { 1 , 4 , 6 , 10 } ; int arr4 [ ] = { 2 , 4 , 7 , 8 } ; int n = arr1 . length ; int x = 30 ; System . out . println ( " Count ▁ = ▁ " + countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) ) ; } }