Ahmad Zughayyer Ahmad Zughayyer - 5 months ago 10
Javascript Question

why does forEach function gives wrong output?

Challenge
Using the JavaScript language, have the function


ArrayAdditionI(arr) take the array of numbers stored in arr 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: if arr 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.
// Sample Test Cases
// Input:5,7,16,1,2
// Output:"false"
//
// Input:3,5,-1,8,12
// Output:"true"

function findLargest(array){
var largest = array[0];

array.forEach(function(num){
if(num > largest){
largest = num;
}
});
return largest;
}

function ArrayAdditionI(array){
var largest = findLargest(array);
var index = array.indexOf(largest);
array.splice(index,1);

array.forEach(function(num,idx){
var sum = 0;
for(var j=0; j<array.length; j++){
if(num === array[j]){
continue;
}else{
sum+=array[j];
}
}
if(sum === largest){
return true;
}
});
return false;
}

console.log(ArrayAdditionI([4, 6, 23, 10, 1, 3]));


Hello everyone!!,
The output of this ArrayAdditionI function should be true, but for some unknown reason it is returning false.However, I found out that it's because of the forEach function because when I used forLoop instead, it worked fine. Does anyone know why whenever I use the forEach it gives me false output? and why is this happening ??

MT0 MT0
Answer

my goal is to know that if any sum of the array elements are equal to the largest number in the array.

You can do it using:

function containsSumToMaximum( array ){
  array.sort( function(a,b){ return a < b ? -1 : 1; } );
  var max = array.pop();
  for ( var i = 3; i < 2 << array.length; i++ )
  {
    var sum   = 0,
        count = 0;
    for ( var j = 0; j < array.length; j++ )
    {
      if ( i & (2 << j) )
      {
        sum += array[j];
        count++;
      }
      if ( sum > max )
        break;
    }
    if ( sum == max && count > 1 )
      return true;
  }
  return false;
}

For an array of n elements there are 2^n -1 ways of summing one-or-more of those elements. The algorithm above just does a brute-force search of all those possible sums and considers whether each sums to the maximum value and that the sum is made up of two-or-more elements.