This variable x contains the number to be checked for the array. var x = 10; var ary = [ 3,5 ]
I want to check if x be summed up by any key combination in ary , and then show which keys add up to make x .
In this case, 3 cannot be used. Thus, the result will be = 5, 5 if x = 10 (because the function should look for the array and find that 5 + 5 is equal to 10)
The length of the array and x are unknown. I do not use libraries. Here's how far I have come so far:
var x = 10; var ary = [ 3, 5 ]; function cycle(){ var result; for( var i = 0; i < ary.length; i++ ){ if( ary[ i ] + ary[ i ] == x ){ result = ary[ i ] + ',' + ary[ i ]; } else if( ary[ i ] + ary[ i + 1 ] == x ){ result = ary[ i ] + ',' + ary[ i + 1 ]; } else if( ary[ i + 1 ] + ary[ i + 1 ] == x ){ result = ary[ i + 1 ] + ',' + ary[ i + 1 ]; } return result; } } var result = cycle(); document.write( result );
I know that the code above is terrible, not flexible, and only works in the specific case in which I use it. How to include all possible combinations?
Assuming the array still has 2 values 3 and 5 , here are some more examples of how the result will be obtained based on x:
if x = 8 , the result will be = 3, 5 ;
if x = 15 , the result will be = 5, 5, 5
if x = 9 , the result will be = 3, 3, 3 , etc.
Note There should be no restriction on how many times the key can be used.
user6597020
source share