javascript - why does forEach function gives wrong output? -
challenge using javascript language, have function
arrayadditioni(arr) take array of numbers stored in arr , return //the string true if combination of numbers in array can added //up equal largest number in array, otherwise return //string false. example: if arr contains [4, 6, 23, 10, 1, 3] //output should return true because 4 + 6 + 10 + 3 = 23. array //not empty, not contain same elements, , 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!!, output of arrayadditioni function should true, unknown reason returning false.however, found out it's because of foreach function because when used forloop instead, worked fine. know why whenever use foreach gives me false output? , why happening ??
my goal know if sum of array elements equal largest number in array.
you can using:
function containssumtomaximum( array ){ array.sort( function(a,b){ return < b ? -1 : 1; } ); var max = array.pop(); ( var = 3; < 2 << array.length; i++ ) { var sum = 0, count = 0; ( var j = 0; j < array.length; j++ ) { if ( & (2 << j) ) { sum += array[j]; count++; } if ( sum > max ) break; } if ( sum == max && count > 1 ) return true; } return false; }
for array of n
elements there 2^n -1
ways of summing one-or-more of elements. algorithm above brute-force search of possible sums , considers whether each sums maximum value , sum made of two-or-more elements.
Comments
Post a Comment