Are the x,y and row, col attributes of a two-dimensional array backwards?
It doesn't matter how you store your data in the array ([x][y] or [y][x]). What does matter is that you always loop over the array in a contiguous way. A java two dimensional array is essentially a one dimensional array storing the second array (eg. in the case of [y][x] you have a long array of [y] in which each y holds the corresponding [x] arrays for that line of y).
To efficiently run through the whole array, it's important to access the data in a way so that you don't continuously have to do searches in that array, jumping from one y-array-of-xarrays to another y-array-of-xarrays. What you want to do is access one y element and access all the x's in there before moving to the next y element.
So in an Array[y][x] situation. always have the first variable in the outer loop and the second in the inner loop:
for (int ys = 0; ys < Array.length; ys++)
for (int xs = 0; xs < Array[y].length; xs++)
{
do your stuff here
}
And of course pre-allocate both Array.lengths out of the loop to prevent having to get those values every cycle.
You have it right, and it does feel a bit backwards. The row number is a y coordinate, and the column number is an x coordinate, and yet we usually write row,col but we also usually write x,y.
Whether you want to write your array as [y][x] or [x][y] depends mostly on how much you actually care about the layout of your array in memory (and if you do, what language you use). And whether you want to write functions/methods that can operate on rows or columns in isolation.
If you are writing C/C++ code, arrays are stored in Row Major Order which means that a single row of data can be treated as 1 dimensional array. But a single column of data cannot. If I remember correctly, VB uses column major order, so languages vary. I'd be surprised of C# isn't also row major order, but I don't know.
This is what I do for my own sanity:
int x = array[0].length;
int y = array.length;
And then for every single array call I make, I write:
array[y][x]
This is particulary useful for graphing algorithms and horizontal/vertical matrix flipping.
I love the question. You’re absolutely right. Most of the time we are either thinking (x, y) or (row, col). It was years before I questioned it. Then one day I realized that I always processed for loops as if x was a row and y was a column, though in plane geometry it’s actually the opposite. As mentioned by many, it really doesn’t matter in most cases, but consistency is a beautiful thing.