Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate sequentially assigned number in grid to x-y coordinates

Tags:

algorithm

Say I have a grid of 5x5, with each cell in the grid numbered from 0-24, going from left to right. Given a cell number such as 17, how do I determine that cell's x and y coordinates? I've been able to do it vice versa, where if given the coordinates I can calculate cell number:

Cellnumber = x + y∗width
(The x and y coordinates represent the upper left point of each cell)

But now I want the opposite. Any ideas?

like image 986
Snowman Avatar asked Sep 04 '25 01:09

Snowman


2 Answers

Assuming 0-based coordinates and a C-like syntax, it would be something like this:

int y = Cellnumber / width;
int x = Cellnumber % width;
like image 55
Jonathan Wood Avatar answered Sep 07 '25 12:09

Jonathan Wood


With the notation that % is the modulus operator:

x = Cellnumber % width  
y = Floor(Cellnumber / width)

So in your 5 x 5 example, Cellnumber = 17

   x = 2
   y = 3
like image 31
Mitch Wheat Avatar answered Sep 07 '25 14:09

Mitch Wheat