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 >_<
Well, I found the whole z1, z2 logic a bit unreadable, so I did it a bit differently:
Prints
[[8], [4, 9], [0, 5, 10], [1, 6, 11], [2, 7], [3]]to the console.How it works
Your matrix construction gives you a rectangle like this (where your
aarray is the set of rows):Which means the diagonals are over this grid:
# # 0 1 2 3 # 4 5 6 7 # 8 9 10 11 # #Now we’re just looping over a skewed rectangle, that would look like this normalised:
Now you’ll notice that for each row you add, you end up with an extra column (starting with a
#) and that the first column is now skewed by this amount (if you imagine holding the first row in place & sliding the rows below to the left). So for our outerforloop (over the columns), the first column is effectively the old first column,0, minus the number of rowsm, plus1, which gives0 - m + 1or1 - m. The last column effectively stays in place, so we’re still looping ton. Then its just a matter of taking each column & looping over each of themrows (innerforloop).Of course this leaves you with a bunch of
undefineds (the#s in the grid above), but we can skip over them with a simpleifto make sure ouri&jare within them&nbounds.Probably slightly less efficient than the
z1/z1version since we’re now looping over the redundant#cells rather than pre-calculating them, but it shouldn’t make any real world difference & I think the code ends up much more readable.