views:

85

answers:

3

if I think of the x,y coordinate plane x,y is the common notation for an ordered pair, but if I use a two-dime array I have myArray[row][col] and row is the y and col is the x. Is that backwards or am I just thinking about it wrong? I was thinking it would look like myArray[x][y] but that's wrong if I want real rows and columns (like in a gameboard.) Wouldn't it be myArray[y][x] to truly mimic a row column board?

A: 

Actually, It's up to you. There is no right of thinking in your question. For example i usually think of a one-dimension array as a row of cell. So, in my mind it is array[col][row]. But it is really up to you...

anthares
If you're thinking of cache consequences, there *is* a right way of looking at it...
Michael Myers
@mmeyers: Not really, the effect is that you store the game-board sideways. It's common to store images this way.
Joel
I think that the question is without any given context ... Of course in different contexts, there is different logics.
anthares
@Joel: 1) As long as you still iterate correctly regardless of how you're thinking about it, yes. That might require going (in your perspective) column-by-column rather than row-by-row. 2) I don't get notified when you call me mmeyers. That's the fourth time that's happened since notifications were implemented. :)
Michael Myers
A: 

I bet there are a lot of differing opinions on this one. Bottom line is, it doesn't really matter as long as you are consistent. If you have other libraries or similar that is going to use the same data it might make sense to do whatever they do for easier integration.

If this is strictly in your own code, do whatever you feel comfortable with. My personal preference would be to use myArray[y][x]. If they are large, there might be performance benefits of keeping the items that you are going to access a lot at the same time together. But I wouldn't worry about that until at a very late stage if at all.

villintehaspam
+4  A: 

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] depends or [x][y] depends mostly on how much you actually care about the layout 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.

John Knoeller