Skip to content

Instantly share code, notes, and snippets.

@JackKell
Created November 23, 2019 23:13
Show Gist options
  • Save JackKell/30a44a4366cda02ce1fd74180443834f to your computer and use it in GitHub Desktop.
Save JackKell/30a44a4366cda02ce1fd74180443834f to your computer and use it in GitHub Desktop.
from typing import Tuple
class Point:
def __init__(self, x: int = 0, y: int = 0):
self.x: int = x
self.y: int = y
def magnitude(self):
return abs(self.x) + abs(self.y)
def value(self):
return self.x, self.y
def getRingInfo(value) -> Tuple[int, int]:
ringIndex = 0
ringSize = 1
while value > ringSize * ringSize:
ringIndex += 1
ringSize += 2
return ringIndex, ringSize
def getMemoryDistance(targetMemoryLocation: int) -> int:
ringIndex, ringSize = getRingInfo(targetMemoryLocation)
spiralDistance = ringSize * ringSize - targetMemoryLocation
position: Point = Point(ringIndex, -ringIndex)
ringSizeMinus1 = ringSize - 1
# Bottom edge leftwards
if spiralDistance > 0:
delta = min(ringSizeMinus1, spiralDistance)
spiralDistance -= delta
position.x -= delta
# Left edge upwards
if spiralDistance > 0:
delta = min(ringSizeMinus1, spiralDistance)
spiralDistance -= delta
position.y += delta
# Top edge rightwards
if spiralDistance > 0:
delta = min(ringSizeMinus1, spiralDistance)
spiralDistance -= delta
position.x += delta
# Right edge downwards
if spiralDistance > 0:
delta = min(ringSize - 2, spiralDistance)
spiralDistance -= delta
position.y -= delta
return position.magnitude()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment