Find four elements that sum to a given value | Set 2 | C ++ program to find four elements with the given sum ; Function to find 4 elements that add up to given sum ; Iterate from 0 to temp . length ; Iterate from 0 to arr . length ; Iterate from i + 1 to arr . length ; Store curr_sum = arr [ i ] + arr [ j ] ; Check if X - curr_sum if present in map ; Store pair having map value X - curr_sum ; Print the output ; Program for two Sum ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void fourSum ( int X , int arr [ ] , map < int , pair < int , int > > Map , int N ) { int temp [ N ] ; for ( int i = 0 ; i < N ; i ++ ) temp [ i ] = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { int curr_sum = arr [ i ] + arr [ j ] ; if ( Map . find ( X - curr_sum ) != Map . end ( ) ) { pair < int , int > p = Map [ X - curr_sum ] ; if ( p . first != i && p . second != i && p . first != j && p . second != j && temp [ p . first ] == 0 && temp [ p . second ] == 0 && temp [ i ] == 0 && temp [ j ] == 0 ) { cout << arr [ i ] << " , " << arr [ j ] << " , " << arr [ p . first ] << " , " << arr [ p . second ] ; temp [ p . second ] = 1 ; temp [ i ] = 1 ; temp [ j ] = 1 ; break ; } } } } } map < int , pair < int , int > > twoSum ( int nums [ ] , int N ) { map < int , pair < int , int > > Map ; for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { Map [ nums [ i ] + nums [ j ] ] . first = i ; Map [ nums [ i ] + nums [ j ] ] . second = j ; } } return Map ; } int main ( ) { int arr [ ] = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 91 ; map < int , pair < int , int > > Map = twoSum ( arr , n ) ; fourSum ( X , arr , Map , n ) ; return 0 ; }