Ok, so I’m writing a program in which I have a grid. The grid is stored in a numbered array, and therefore each grid has an index (everything is zero-based). Now, I want to be able to access each cell/element by the index as well as by x,y coordinates. I’ve figured out functions to do this conversion easily, and I’m pretty sure they’re solid, but I’m a little weak on the math part of this so I’d like verification that they always work.
Example Grid:
+-------+-------+-------+-------+
| (0,0) | (1,0) | (2,0) | (3,0) |
| 0 | 1 | 2 | 3 |
+-------+-------+-------+-------+
| (0,1) | (1,1) | (2,1) | (3,1) |
| 4 | 5 | 6 | 7 |
+-------+-------+-------+-------+
| (0,2) | (1,2) | (2,2) | (3,2) |
| 8 | 9 | 10 | 11 |
+-------+-------+-------+-------+
| (0,3) | (1,3) | (2,3) | (3,3) |
| 12 | 13 | 14 | 15 |
+-------+-------+-------+-------+
To convert from (x,y) to n, for width of grid w:
n = (w*(y+1)) - (w-x)
To convert from n to (x,y), for width of grid w:
y = RoundDown(n / w)
x = n - (w * y)
I tested these functions on a variety of grid sizes and couldn’t find anything wrong with them. Does anyone see a problem?
Also, if there is a better way to do this, I’m open to suggestions
TIA!
–FCOD