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 print ( count ) ; 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 ; four sorted arrays each of size ' n '
def countPairs ( arr1 , arr2 , n , value ) : NEW_LINE INDENT count = 0 NEW_LINE l = 0 NEW_LINE r = n - 1 NEW_LINE while ( l < n and r >= 0 ) : NEW_LINE INDENT sum = arr1 [ l ] + arr2 [ r ] NEW_LINE if ( sum == value ) : NEW_LINE INDENT l += 1 NEW_LINE r -= 1 NEW_LINE count += 1 NEW_LINE DEDENT elif ( sum > value ) : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT l += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT p_sum = arr1 [ i ] + arr2 [ j ] NEW_LINE count += int ( countPairs ( arr3 , arr4 , n , x - p_sum ) ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr1 = [ 1 , 4 , 5 , 6 ] NEW_LINE arr2 = [ 2 , 3 , 7 , 8 ] NEW_LINE arr3 = [ 1 , 4 , 6 , 10 ] NEW_LINE arr4 = [ 2 , 4 , 7 , 8 ] NEW_LINE n = len ( arr1 ) NEW_LINE x = 30 NEW_LINE print ( " Count ▁ = ▁ " , countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) ) NEW_LINE