Find four elements that sum to a given value | Set 2 | Javascript 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
class pair { constructor ( first , sec ) { this . first = first ; this . sec = sec ; } } function fourSum ( X , arr , map ) { let temp = new Array ( arr . length ) ; for ( let i = 0 ; i < temp . length ; i ++ ) temp [ i ] = 0 ; for ( let i = 0 ; i < arr . length - 1 ; i ++ ) { for ( let j = i + 1 ; j < arr . length ; j ++ ) { let curr_sum = arr [ i ] + arr [ j ] ; if ( map . has ( X - curr_sum ) ) { let p = map . get ( X - curr_sum ) ; if ( p . first != i && p . sec != i && p . first != j && p . sec != j && temp [ p . first ] == 0 && temp [ p . sec ] == 0 && temp [ i ] == 0 && temp [ j ] == 0 ) { document . write ( arr [ i ] + " " + arr [ j ] + " " + arr [ p . first ] + " " + arr [ p . sec ] ) ; temp [ p . sec ] = 1 ; temp [ i ] = 1 ; temp [ j ] = 1 ; break ; } } } } } function twoSum ( nums ) { let map = new Map ( ) ; for ( let i = 0 ; i < nums . length - 1 ; i ++ ) { for ( let j = i + 1 ; j < nums . length ; j ++ ) { map . set ( nums [ i ] + nums [ j ] , new pair ( i , j ) ) ; } } return map ; } let arr = [ 10 , 20 , 30 , 40 , 1 , 2 ] ; let n = arr . length ; let X = 91 ; let map = twoSum ( arr ) ; fourSum ( X , arr , map ) ;