Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert index to grid coordinate mathematically

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 divs or mods, 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...

like image 432
Christian Avatar asked Sep 13 '12 08:09

Christian


1 Answers

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
like image 155
Cyprian Avatar answered Sep 28 '22 05:09

Cyprian