Find four elements that sum to a given value | Set 1 ( n ^ 3 solution ) | A naive solution to print all combination of 4 elements in A [ ] with sum equal to X ; Fix the first element and find other three ; Fix the second element and find other two ; Fix the third element and find the fourth ; find the fourth ; Driver Code
function findFourElements ( A , n , X ) { for ( let i = 0 ; i < n - 3 ; i ++ ) { for ( let j = i + 1 ; j < n - 2 ; j ++ ) { for ( let k = j + 1 ; k < n - 1 ; k ++ ) { for ( let l = k + 1 ; l < n ; l ++ ) if ( A [ i ] + A [ j ] + A [ k ] + A [ l ] == X ) document . write ( A [ i ] + " " + A [ j ] + " " + A [ k ] + " " + A [ l ] ) ; } } } } let A = [ 10 , 20 , 30 , 40 , 1 , 2 ] ; let n = A . length ; let X = 91 ; findFourElements ( A , n , X ) ;