Skip to content

Instantly share code, notes, and snippets.

@ronivaldo
Created November 3, 2019 20:49
Show Gist options
  • Save ronivaldo/863008988dbc0ad1ec34e1b55b7e3ef5 to your computer and use it in GitHub Desktop.
Save ronivaldo/863008988dbc0ad1ec34e1b55b7e3ef5 to your computer and use it in GitHub Desktop.
Hanna moves in a lattice
# Hanna moves in a lattice where every point can be represented by a pair of integers.
# She moves from point A to point B and then takes a turn 90 degrees rightand starts
# moving till she reaches the first point on the lattice. Find what's the
# point she would reach?
# A' . |
# . |
# . | . . . A
# . | .
# -------------------------
# |
# |
# |
#
# When you rotate clockwise a point A 90 degrees from origin,
# you get A' => f(x,y) = (-y, x)
#
#
# | A
# | .
# | B
# | .
# | .
# ----------O-------------
# |
# |
# |
#
# Based on a point A from origin, you can find point B by:
# By/Ay = Bx/Ax => By = Bx * Ay/Ax
#
# |
# A |
# . |
# . |
# . |
# ----------B--------------
# . |
# . |
# C |
#
# To make things easier, we can move the points to get point B on origin.
# After Hanna rotate 90 degrees to the right on point B,
# she will find eventually point C.
# Let say that D is a point in a rect that is on B-C.
# Hanna will stop on a point on the lattice when the point (x,y) is integer
# So, from B we need to iterate Dx until we find a Dy integer
#
def rotate_90_clockwise(A):
return (-A[1], A[0])
def find_B_y(A, x):
return x * A[1]/A[0] if A[0] else A[1]
def find_next(A, B):
# make B the origin
Ao = (A[0] - B[0], A[1] - B[1])
Bo = (0,0)
# rotate Ao 90 clockwise
C = rotate_90_clockwise(Ao)
if C[0] == 0:
# C is on y axis
x = 0
# Dy is one unit from origin
y = C[1]/abs(C[1])
else:
found = False
# from origin
x = 0
while not found:
# inc x one unit
x += C[0]/abs(C[0])
y = find_B_y(C, x)
# check if y is integer
found = y == round(y)
# move back from origin
x, y = (x + B[0], y + B[1])
return x, y
A = (-2, 3)
B = (3, 2)
D = find_next(A, B)
print(D)
B = (-4, 2)
A = (-2, 2)
D = find_next(A, B)
print(D)
B = (1, 20)
A = (1, 5)
D = find_next(A, B)
print(D)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment