简体   繁体   中英

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM