Return Largest Numbers in Arrays- 3 out of 4

Return Largest Numbers in Arrays- 3 out of 4
0

#1

Tell us what’s happening:
I had solved this Algorithm before the new lessons came out earlier this summer. I was redoing some old algorithms for good measure and I’m having trouble passing this again. I don’t understand why it passes only 3 of the 4 tests. It seems like it should be all or nothing.

Thoughts?

Your code so far


function largestOfFour(arr) {
  let largestArr = [];
  for (var i=0; i<arr.length; i++)
  {
    let largestNum=0;
    for (var j=0; j<arr.length; j++)
    {
      if(largestNum<arr[i][j])
      {
        largestNum=arr[i][j];
      }
    }
    largestArr.push(largestNum);
  } 
  return largestArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays


#2

Because the tests are more robust now and include sub arrays with all negative numbers. This causes your use of largestNum = 0 to be a problem.


#3

your program does not solve the 4th case

largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])

because this includes negative numbers. And you are initializing your largestNum to zero.
Try initializing it to a value lower than the lowest value in this array of arrays.


#4

I see. So is there something I can use that basically means “any integer goes here”? I feel like simply putting -1000 and knowing it fits the parameters is kind of cheating.


#5

What I would suggest is the following.
A the beginning of every subArray, consider that the first number is the largest number, and then compare it to other elements of the array through iteration. Every time you find a number larger than yourLargestNumber, swap them till the end of the Subarray.
Repeat the process for the next subarray

Hope it helped!