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 program to test above function
< ? php function findFourElements ( $ A , $ n , $ X ) { for ( $ i = 0 ; $ i < $ n - 3 ; $ i ++ ) { for ( $ j = $ i + 1 ; $ j < $ n - 2 ; $ j ++ ) { for ( $ k = $ j + 1 ; $ k < $ n - 1 ; $ k ++ ) { for ( $ l = $ k + 1 ; $ l < $ n ; $ l ++ ) if ( $ A [ $ i ] + $ A [ $ j ] + $ A [ $ k ] + $ A [ $ l ] == $ X ) echo $ A [ $ i ] , " , ▁ " , $ A [ $ j ] , " , ▁ " , $ A [ $ k ] , " , ▁ " , $ A [ $ l ] ; } } } } $ A = array ( 10 , 20 , 30 , 40 , 1 , 2 ) ; $ n = sizeof ( $ A ) ; $ X = 91 ; findFourElements ( $ A , $ n , $ X ) ; ? >