Reputation: 101
I have gone over my code a million times and can't figure out the problem. I have made a code that will return all the possible sums of numbers within an array. It works fine when there are 3 numbers in the array but if I add another number to the array it replaces a few of what should be sums with NaN. Ex:
array = [4, 6, 3, 7] is returning:
[ 20, 16, 10, 13, 9, 14, 11, 7, 17, NaN, 13 ] and NaN should be "10"
array = [4, 6, 3, 7];
newarray = [0];
for (i = 0; i < array.length; i++) {
newarray[0] += array[i];
}
x = 0;
y = 1;
for (i = 0; i < array.length; i++) {
newarray.push((newarray[0]-array[i]));
if (i !== 0) {
y = y+array.length;
}
x = i;
while (x < array.length) {
if (x != i) {
newarray.push((newarray[y]-array[x]));
}
x++;
}
}
console.log(newarray);`
The fact that I am getting NaN in some slots where numbers should be leads me to believe there is a problem with variable x in the while loop but my brain is being racked on where the issue actually is. http://jsfiddle.net/nsjY6/
Upvotes: 0
Views: 625
Reputation: 8156
newarray[y] here cause NaN
newarray.push((newarray[y - 1]-array[x]));
[ 20, 16, 14, 17, 13, 14, 10, 6, 17, 10, 13 ]
add my version
var array = [4, 6, 3, 7];
var newarray = [];
for (i=0; i< Math.pow(2, array.length); i++) {
var s = i.toString(2)
var t = 0;
for (c in s) t += s[c] * array[c];
newarray.push(t);
}
console.log(newarray);
Upvotes: 2