Skip to content

Instantly share code, notes, and snippets.

@jasper-lyons
Created December 4, 2017 07:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasper-lyons/6c7b0afb180be4def6e705d701835f29 to your computer and use it in GitHub Desktop.
Save jasper-lyons/6c7b0afb180be4def6e705d701835f29 to your computer and use it in GitHub Desktop.
position-in-spiral.py
# got a huge ammount of help from https://stackoverflow.com/questions/11550153/determine-position-of-number-in-a-grid-of-numbers-centered-around-0-and-increasi
def sequence(i):
n = 2 * i - 1
return n * n
def layer(i):
return math.floor((math.sqrt(i) + 1) / 2)
def length(i):
return 8 * i
def sector(i):
return math.floor(4 * (i - sequence(layer(i))) / length(layer(i)))
def position(i):
l = layer(i)
s = sector(i)
offset = i - sequence(l) - s * length(l) // 4
if s == 0.0:
return -l, -l + offset + 1
if s == 1.0:
return -l + offset - 1, l
if s == 2.0:
return l, l - offset - 1
return l - offset - 1, -l
pos = position(265148) # everything is minus 1 so 265149 -> 265148
steps = abs(pos[0]) + abs(pos[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment