[英]How to convert grid number to coordinates when the rows alternate order
7|8|9
6|5|4
1|2|3
1 -> (1,1)
2 -> (2,1)
3 -> (3,1)
4 -> (3,2)
5 -> (2,2)
6 -> (1,2)
7 -> (1,3)
8 -> (2,3)
9 -> (3,3)
In this grid, the mapping of the numbers to coordinates is shown above.在这个网格中,数字到坐标的映射如上所示。
I'm struggling to come up with a formula where given the number of the grid and the number of rows and columns in the grid, it outputs the coordinates of the grid.我正在努力想出一个公式,其中给定网格的数量以及网格中的行数和列数,它输出网格的坐标。
I tried following the logic in this question but in this question , the coordinate system starts from 0 and the rows are not alternating.我尝试按照这个问题中的逻辑进行操作,但是在这个问题中,坐标系从 0 开始并且行不是交替的。
If there was no alternating and the numbers were all starting at 0 and not 1, then you could apply Euclidean division directly:如果没有交替并且数字都从 0 而不是 1 开始,那么您可以直接应用欧几里德除法:
x = n % 3
y = n // 3
where //
gives the quotient of the Euclidean division, and %
gives the remainder of the Euclidean division.其中
//
给出欧氏除法的商, %
给出欧氏除法的余数。
If there was no alternating, but the numbers all start at 1 instead of 0, then you can fix the above formula by removing 1
from n
to make it start at 0, then adding 1 to x
and y
to make them start at 1:如果没有交替,但数字都从 1 而不是 0 开始,那么您可以通过从
n
中删除1
使其从 0 开始,然后将 1 添加到x
和y
使它们从 1 开始来修复上面的公式:
x = ((n - 1) % 3) + 1
y = ((n - 1) // 3) + 1
Now all we have to change to take the alternating into account is to flip the x values on the right-to-left rows.现在我们必须改变以考虑交替的情况是翻转从右到左行的 x 值。
y
remains unchanged, and x
remains unchanged on the left-to-right rows. y
保持不变, x
在从左到右的行中保持不变。
The right-to-left rows are the rows with an even y
, and you can flip x
symmetrically around 2
by removing it from 4
:从右到左的行是偶数
y
的行,您可以通过将x
从4
中删除来围绕2
对称地翻转它:
if y % 2 == 0:
x = 4 - x
Putting it all together in a function and testing it, in python:将它们全部放在 function 中并在 python 中进行测试:
def coord(n):
y = ((n-1) // 3) + 1
x = ((n-1) % 3) + 1
if y % 2 == 0: # right-to-left row
x = 4 - x # flip horizontally
return (x, y)
for n in range(1, 9+1):
x, y = coord(n)
print(f'{n} -> ({x},{y})')
Output: Output:
1 -> (1,1)
2 -> (2,1)
3 -> (3,1)
4 -> (3,2)
5 -> (2,2)
6 -> (1,2)
7 -> (1,3)
8 -> (2,3)
9 -> (3,3)
The inverse operation of a Euclidean division is a multiplication and an addition:欧氏除法的逆运算是乘法和加法:
if y % 2 == 1:
n = 3 * (y-1) + x
else:
n = 3 * (y-1) + 4 - x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.