5

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

Christian
  • 27,509
  • 17
  • 111
  • 155
  • Javascript answer in this thread: https://stackoverflow.com/questions/5494974/convert-1d-array-index-to-2d-array-index/54569733#54569733 – Ska Feb 07 '19 at 10:12

1 Answers1

16

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
Cyprian
  • 11,174
  • 1
  • 48
  • 45