Count quadruples from four sorted arrays whose sum is equal to a given value x | function to count all quadruples from four sorted arrays whose sum is equal to a given value x ; unordered_map ' um ' implemented as hash table for < sum , frequency > tuples ; count frequency of each sum obtained from the pairs of arr1 [ ] and arr2 [ ] and store them in 'um   ; generate pair from arr3 [ ] and arr4 [ ] ; calculate the sum of elements in the pair so generated ; if ' x - p _ sum ' is present in ' um ' then add frequency of ' x - p _ sum ' to ' count ' ; required count of quadruples ; four sorted arrays each of size n
def countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) : NEW_LINE INDENT count = 0 NEW_LINE m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( arr1 [ i ] + arr2 [ j ] ) in m : NEW_LINE INDENT m [ arr1 [ i ] + arr2 [ j ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ arr1 [ i ] + arr2 [ j ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT for k in range ( n ) : NEW_LINE INDENT for l in range ( n ) : NEW_LINE INDENT p_sum = arr3 [ k ] + arr4 [ l ] NEW_LINE if ( x - p_sum ) in m : NEW_LINE INDENT count += m [ x - p_sum ] NEW_LINE DEDENT 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