This variable x
contains a number that needs to be tested against an array.
var x = 10; var ary = [ 3,5 ]
I want to test if x
can be made up by the sum of any combination of the keys in ary
, then show what keys do add up to make x
.
In this case the 3
cannot be used. So the result would = 5, 5
if x = 10
( because the function should search the array and find that 5 + 5 equals 10 )
The length of the array and x are not known. I'm not using any libraries. This is how far I've come thus 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 the above code is terrible, not flexible in the least, and only works in that particular case I use it for. How would I include all possible combinations?
Assuming the array still only has the 2 values 3
and 5
, here are more examples how what result would get based on x:
if x = 8
, result would = 3, 5
;
if x = 15
, result would = 5, 5, 5
if x = 9
, result would = 3, 3, 3
etc.
Note: There should be no limit to how many times a key can be used.