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
using System ; using System . Collections . Generic ; class GFG { static void fourSum ( int X , int [ ] arr , Dictionary < int , Tuple < int , int > > Map , int N ) { int [ ] temp = new int [ 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 . ContainsKey ( X - curr_sum ) ) { Tuple < int , int > p = Map [ X - curr_sum ] ; if ( p . Item1 != i && p . Item2 != i && p . Item1 != j && p . Item2 != j && temp [ p . Item1 ] == 0 && temp [ p . Item2 ] == 0 && temp [ i ] == 0 && temp [ j ] == 0 ) { Console . Write ( arr [ i ] + " , " + arr [ j ] + " , " + arr [ p . Item1 ] + " , " + arr [ p . Item2 ] ) ; temp [ p . Item2 ] = 1 ; temp [ i ] = 1 ; temp [ j ] = 1 ; break ; } } } } } static Dictionary < int , Tuple < int , int > > twoSum ( int [ ] nums , int N ) { Dictionary < int , Tuple < int , int > > Map = new Dictionary < int , Tuple < int , int > > ( ) ; for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { Map [ nums [ i ] + nums [ j ] ] = new Tuple < int , int > ( i , j ) ; } } return Map ; } static void Main ( ) { int [ ] arr = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = arr . Length ; int X = 91 ; Dictionary < int , Tuple < int , int > > Map = twoSum ( arr , n ) ; fourSum ( X , arr , Map , n ) ; } }