Traverse 2D Array (Matrix) Diagonally

Posted by jonobr1 on Stack Overflow See other posts from Stack Overflow or by jonobr1
Published on 2010-05-19T04:12:41Z Indexed on 2010/05/19 4:20 UTC
Read the original article Hit count: 731

So I found this thread that was extremely helpful in traversing an array diagonally. I'm stuck though on mirroring it. For example:

var m = 3;
var n = 4;
var a = new Array();
var b = 0;

for(var i = 0; i < m; i++) {
  a[i] = new Array(n);
  for(var j = 0; j < n; j++) {
    a[i][j] = b;
      b++;
  }
}

for (var i = 0; i < m + n - 1; i++) {
  var z1 = (i < n) ? 0 : i - n + 1;
  var z2 = (i < m) ? 0 : i - m + 1;
  for (var j = i - z2; j >= z1; j--) {
    console.log(a[j][i - j]);
  }
}

Console reads [[0],[4,1],[8,5,2],[9,6,3],[10,7],[11]]

I'd like it to read [[8],[4,9],[0,5,10],[1,6,11],[2,7],[3]]

Been stumped for awhile, it's like a rubik's cube >_<

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about 2d-array