Max Van de Velde
Max Van de Velde

Reputation: 27

Loop through 2d-array diagonally

I've been searching on this website for an valid answer for my question so far i haven't find one so i'm posting a question

I have to loop trough an 2d-array diagonally to check if the value === 0. Whenever i try this it only goes trough the array of the 2d-array and then it stops

Basically i need to get the indices 0,0 1,1 2,2...

function isValidDistanceMatrix(nss) {
    let row_count = nss.length;
    let row_sizes = nss.map(ns => ns.length);
    let maxRow = Math.max(...row_sizes);
    let min = Math.min(...row_sizes);

    if (maxRow === row_count && min === maxRow){
       for (let x = 0; x < row_count; x++){
                   if (nss[x][x] === 0){
                       return true;
                   }
               }
           }
    return false;
}

[[0, 5, 6, 1], [5, 0, 1, 1], [6, 1, 0, 1], [1, 1, 1, 0]] returns true

[[0, 5, 6, 1], [5, 4, 1, 1], [6, 1, 5, 7], [1, 1, 1, 0]] returns false

Upvotes: 0

Views: 68

Answers (1)

Slai
Slai

Reputation: 22876

You are returning true after checking the first value instead of checking all of the values.
Change it to return false for any non-zero value, and return true at the end :

function isValidDistanceMatrix(nss) {
  let row_count = nss.length;
  let row_sizes = nss.map(ns => ns.length);
  let maxRow = Math.max(...row_sizes);
  let min = Math.min(...row_sizes);

  if (maxRow !== row_count || min !== row_count) return false;  // change to return false

  for (let x = 0; x < row_count; x++) {
    if (nss[x][x] !== 0) {              // change to not equal
      return false;                     // change to false on the first non-zero
    }
  }

  return true;                          // change to return true after all values are checked
}

Alternatively, it can be simplified with the Array.prototype.every() method (not tested) :

const isValidDistanceMatrix = nss => 
                    nss.every((row, index) => row.length === nss.length && row[index] === 0);

Upvotes: 2

Related Questions