Refactor this loop to do more than one iteration

Viewed 1088

Here I am trying to find the four diagonally adjacent numbers in a 20*20 grid whose product is the greatest. Diagonals run from upper left to lower right. But something is wrong with the first loop: it does not iterate over the array. I could not find what it is.

function fouradjacentFinder(){
  let mystring = "08 02 22 97 38 15 ..."
   let  myarray  = mystring.split(" ").map(x =>Number(x));
    let counter ;
     let max = -Infinity;


 for(let i = 0;i<myarray.length;i++){
   counter= 0 ;

   for(let k =21;;k+21 ){
    myarray[i] = myarray[i]*myarray[k];
       counter++

     if(counter>4){
        break;
       }

   if(myarray[i]>max){
     max = myarray[i] ;
   }
   console.log(max)
  

 }
 return max;
 }
}
1 Answers

Several issues:

  • Your indentation is off, and thereby you missed the fact that the return statement occurs within the for loop: so it only performs one iteration. Always properly indent your code.
  • k+21 does not modify k. You'll want to do k+=21
  • myarray[k] is independent from the value of i, which cannot be right. Either add i to that index, or define k so that it includes the value of i.
  • i should not iterate as far as myarray.length, as in the last few rows there is no possibility to have a diagonal that has 4 values. The loop should stop earlier.

So here is your code corrected:

function fouradjacentFinder(){
    let mystring = "08 02 22 97 38 15 ..."
    // No need to have an anonymous function wrapper around Number
    let myarray  = mystring.split(" ").map(Number); 
    let max = -Infinity;

    for (let i = 0; i + 3*21 < myarray.length; i++) { // Limit i
        // Better not update myarray[i] and use separate variable
        let product = 1; 

        for (let k = i; k < i+4*21; k += 21) { // fix k
            product *= myarray[k];
        }

        if (product > max){
            max = product;
        }
    }
    return max; // outside loop
}
Related