Given that
$c = 2; // number of columns
$r = 3; // number of rows
I need to find the x,y
grid coordinate of the value of $i
which is the index of a particular cell (left->
right, top->
bottom order).
Usually, one would work this out using two loops; a loop for rows and another one for columns, but in my case, I need to do this mathematically.
So with the above case, I would have something like:
$grid = new Grid(2, 3);
// i x y
list($x, $y) = $grid->getCoordOfCell(0); // 0 0 0
list($x, $y) = $grid->getCoordOfCell(1); // 1 1 0
list($x, $y) = $grid->getCoordOfCell(2); // 2 0 1
list($x, $y) = $grid->getCoordOfCell(3); // 3 1 1
list($x, $y) = $grid->getCoordOfCell(4); // 4 0 2
list($x, $y) = $grid->getCoordOfCell(5); // 5 1 2
Hypothetically, getCoordOfCell()
would return an array of x,y
coordinates for grid cell $i
.
Don't know if I missed something here, but I think this is pretty much it.
I guess the resulting mathematical formula would be based on div
s or mod
s, but I just don't have the mental strength to think this over myself. Plus, I'm sure that as a question this should be useful to others in the future. Oh, although I'm talking PHP here, this is probably language agnostic...
To get right column you have:
$i % NUMBER_ITEMS_IN_ROW
And to get right row:
$i / NUMBER_ITEMS_IN_ROW
In your example, there are 3 rows and 2 columns (== items in a row), so:
$i $x ($i%2) $y ($i/2)
0 0 0
1 1 0
2 0 1
3 1 1
4 0 2
5 1 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With