(In the editor: I added a second function that allows you to get the Cartesian coordinate version directly.)
, . , , , , . , 8 . 1. , y, - . , , . Python:
from math import sqrt, ceil
def coordinates(m):
n = ceil(sqrt(m)/2)
i = m - 4*(n-1)**2
if i <= n:
return (n,-i)
elif i <= 2*n-1:
return (2*n - i, -n)
elif i <= 3*n - 1:
return (2*n - 1 - i, -n)
elif i <= 4*n - 2:
return (-n, -4*n + 1 + i)
elif i <= 5*n - 2:
return (-n, -4*n + 2 + i)
elif i <= 6*n - 3:
return (-6*n + 2 + i, n)
elif i <= 7*n - 3:
return (-6*n + 3 + i,n)
else:
return (n, 8*n -3 - i)
(x, y) (i, j), , , :
def cartesianFromGrid(i,j,w = 1):
x = w * (i if i < 0 else i - 1)
y = w * (j if j > 0 else j + 1)
return (x,y)
, . ( 1 -1 ), , :
def cartCoordinates(m):
n = ceil(sqrt(m)/2)
i = m - 4*(n-1)**2
if i <= n:
return (n-1,-i+1)
elif i <= 3*n - 1:
return (2*n - 1 - i, -n + 1)
elif i <= (5*n - 2):
return (-n, -4*n + 2 + i)
elif i <= 7*n - 3:
return (-6*n + 2 + i, n)
else:
return (n-1, 8 * n - 3 - i)
1-16:
>>> for n in range(1,17):
print(n, ': grid coords =', coordinates(n),
'Cartesian =',cartesianFromGrid(*coordinates(n)))
1 : grid coords = (1, -1) Cartesian = (0, 0)
2 : grid coords = (-1, -1) Cartesian = (-1, 0)
3 : grid coords = (-1, 1) Cartesian = (-1, 1)
4 : grid coords = (1, 1) Cartesian = (0, 1)
5 : grid coords = (2, -1) Cartesian = (1, 0)
6 : grid coords = (2, -2) Cartesian = (1, -1)
7 : grid coords = (1, -2) Cartesian = (0, -1)
8 : grid coords = (-1, -2) Cartesian = (-1, -1)
9 : grid coords = (-2, -2) Cartesian = (-2, -1)
10 : grid coords = (-2, -1) Cartesian = (-2, 0)
11 : grid coords = (-2, 1) Cartesian = (-2, 1)
12 : grid coords = (-2, 2) Cartesian = (-2, 2)
13 : grid coords = (-1, 2) Cartesian = (-1, 2)
14 : grid coords = (1, 2) Cartesian = (0, 2)
15 : grid coords = (2, 2) Cartesian = (1, 2)
16 : grid coords = (2, 1) Cartesian = (1, 1)
:
>>> coordinates(1000000)
(500, 1)
, 1000x1000.
, tkinter:
