I need help solving this question. It just has a bug and I cant find it. Write a
ID: 3882709 • Letter: I
Question
I need help solving this question. It just has a bug and I cant find it.
Write a function that takes an array of integer arrays as input and returns the heaviest array back. The heaviness of an array is just the sum of its values. If no arrays are passed in, return null. function heaviestArray(arrays) { var maxWeight = 0: var heaviest = null: for(var i = 0: maxWeight) { maxHeight = thisWeight: heaviest = thisArray: } } return heaviest: } function arrayweight(array) { var weight = 0: for(var i = 0: iExplanation / Answer
Here the problem is you have set the maxWeight as 0 (zero) ie for numbers greater than zero it will work fine, but in the case of negative numbers 0 will remain always greater so the heaviest will be null .
so here is the solution ie set the maxWeight to the first array's weight and in that condition
if(thisWeigt >maxWeight ) replace it with if(thisWeigt >=maxWeight )
function heaviestArray(arrays){
var maxWeight = arrayWeight(arrays[0]);
var heaviest = null;
for(var i=0;i<arrays.length;i++){
var thisArray = arrays[i];
var thisWeight = arrayWeiht(thisArray);
if(thisWeigt >=maxWeight ) {
maxWeight = thisWeight;
heaviest = thisArray;
}
}
return heaviest;
}
and the next function is same means no error
please try this and comment if not worked
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.