Okay, here's a challenge at Coderbyte that completely stumped me. I came up with a solution, but I know it is flawed.
Have the function
ArrayAdditionI(arr)
take the array of numbers stored inarr
and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false. For example: ifarr
contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.
It is easy enough to find the highest value in the array. If the length of the array was fixed, I could probably come up with a way to test various combinations, but I'm not sure how to handle different arrays. I wonder if the solution involves recursion? Or perhaps there is a way to call a function a number of times depending on the size of the array. Anyway, my "solution" is below. I would love to see a real solution, or if anyone wants to give me some hints, I am happy to give it another try.
function ArrayAdditionI(arr) {
var greatest = -100;
var index = -1;
var sum = 0;
for (var i = 0; i<arr.length; i++){
if (arr[i] > greatest){
greatest = arr[i];
index = i;
}
}
arr.splice(i,1)
for (var i = 0; i<arr.length; i++){
sum += arr[i];
if (greatest = sum){
return true;
}else{
return false;
}
}
}
all
the numbers. Thus I asked for the OP's comment on that which they did not provide. I never understand why someone posts a question and then disappears - not answering clarifying questions that people might ask. \$\endgroup\$