Converting numbers within grid to their corresponding x,y coordinates

≡放荡痞女 提交于 2020-01-01 14:08:14

问题


Given the numbers in the following grid (from 1 to 36), how can I determine their coordinates (x,y) within the grid?

 |  0  1  2  3  4  5  6  7  8
------------------------------
0|  1  2  3  4  5  6  7  8  9
1| 10 11 12 13 14 15 16 17 18
2| 19 20 21 22 23 24 25 26 27
3| 28 29 30 31 32 33 34 35 36

i.e. what I want to obtain is the following:

 |     0     1     2        8
------------------------------
0| (0,0) (1,0) (2,0) ... (8,0)
1| (0,1) (1,1) (2,1) ... (8,1)
2| (0,2) (1,2) (2,2) ... (8,2)
3| (0,3) (1,3) (2,3) ... (8,3)

I have tried:

x = number%9-1;
y = number/9;

which works for all cases except the ones in the last column on the right.

So I came up with:

if (number%9==0) {
    x = 8;
    y = number/9-1;
}
else{
    x = number%9-1;
    y = number/9;
}

My question is, is there a smarter way of doing this?


回答1:


x = (number-1)%9;
y = (number-1)/9;


来源:https://stackoverflow.com/questions/8669189/converting-numbers-within-grid-to-their-corresponding-x-y-coordinates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!