Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to get diagonals of matrix array

I want to get all the diagonals of a matrix array using javascript. Supposing the input and output as follows:

input = [
  [1,2,3],
  [4,5,6],
  [7,8,9],
]

output = [
  [1],
  [4,2],
  [7,5,3],
  [8,6],
  [9],
]

How can I turn the input into the output? How can I do this so that it will work for any size square grid (2x2, 3x3, 4x4, etc.)?

Thanks!

like image 597
Michael Mahony Avatar asked Sep 20 '25 02:09

Michael Mahony


2 Answers

const arr = [
    [11, 2, 4],
    [4, 5, 6],
    [10, 8, 12]
];
function diagonalDifference(arr) {
    const  primaryDiagonal = arr
        .map((e, i) => e[i])
        .reduce((mem, curr) => mem + curr, 0);
    const secondaryDiagonal = arr
        .map((e, i) => {
            let index = arr.length - i -1;
            return e[index];
        })
        .reduce((mem, curr) => mem + curr, 0);
    return Math.abs(primaryDiagonal - secondaryDiagonal);
}
console.log(diagonalDifference(arr));
like image 53
Yami Mahèra Avatar answered Sep 22 '25 16:09

Yami Mahèra


The first way that came to mind (not necessarily the best way) is just to have a loop that runs down the left edge of the square followed by a loop that runs along the bottom edge of the square. In other words, I've written code that does exactly what I would do if getting the diagonals by hand, with no clever optimisations.

Note that this should work for any size square, but doesn't try to cope with rectangles: I leave that as an exercise for the reader.

function getDiagonals(m) {
  var s, x, y, d,
      o = [];
  for (s = 0; s < m.length; s++) {
    d = [];
    for(y = s, x = 0; y >= 0; y--, x++)
      d.push(m[y][x]);
    o.push(d);
  }
  for (s = 1; s < m[0].length; s++) {
    d = [];
    for(y = m.length - 1, x = s; x < m[0].length; y--, x++)
      d.push(m[y][x]);
    o.push(d);
  }
  return o;
}

var output = getDiagonals(input);

I gave it a few brief tests and it seems to work, but you can try for yourself with this demo.

like image 21
nnnnnn Avatar answered Sep 22 '25 16:09

nnnnnn