Last active
April 27, 2017 22:12
-
-
Save shawa/1741f78d0acd1d5e62a35f4a4faaffc5 to your computer and use it in GitHub Desktop.
Linear Algebra-based solution, using linear transformations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from numpy import sin, cos, array, pi | |
from operator import matmul | |
from functools import reduce | |
def move(theta, s): | |
"""Generate a translation and rotation matrix from a given angle theta | |
and displacement s. The transformation rotates the whole coordinate | |
system either left or right, then moves us `s` steps north | |
Given a vector v = [ x y 1 ], and a tranformation matrix A, | |
We perform one move by computing v' = [ x' y' 1 ] = Av | |
""" | |
return array([[cos(theta), -sin(theta), s*cos(theta)], | |
[sin(theta), cos(theta), s*sin(theta)], | |
[0 , 0 , 1]]) | |
def interpet(instructions): | |
"""Moves can be composed by simply multiplying them together, | |
so we get all of the transformation matrices for a list of steps | |
"L1, R4"... etc and get a final tranformation, the matrix product | |
of all of them. | |
""" | |
theta = {'R': pi / 2, 'L': (3 * pi) / 2} | |
return reduce(matmul, (move(theta[s[0]], float(s[1:])) | |
for s in instructions.split(', '))) | |
def travel(instructions): | |
"""Now to follow a set of instructions we multiply a vector | |
representing us being at the origin [0 0 1] by the composite | |
tranformation | |
Our final position is the fist two entries of the resultant | |
vector""" | |
init = array([0, 0, 1]) | |
transformation = interpet(instructions) | |
return (transformation @ init)[:2] | |
def main(): | |
""" | |
To solve this, we then just move to the destination, then take | |
the taxicab distance, abs(x) + abs(y) | |
""" | |
moves = ("L4, L3, R1, L4, R2, R2, L1, L2, R1, R1, L3, R5, L2, R5, " | |
"L4, L3, R2, R2, L5, L1, R4, L1, R3, L3, R5, R2, L5, R2, " | |
"R1, R1, L5, R1, L3, L2, L5, R4, R4, L2, L1, L1, R1, R1, " | |
"L185, R4, L1, L1, R5, R1, L1, L3, L2, L1, R2, R2, R2, L1, " | |
"L1, R4, R5, R53, L1, R1, R78, R3, R4, L1, R5, L1, L4, R3, " | |
"R3, L3, L3, R191, R4, R1, L4, L1, R3, L1, L2, R3, R2, R4, " | |
"R5, R5, L3, L5, R2, R3, L1, L1, L3, R1, R4, R1, R3, R4, " | |
"R4, R4, R5, R2, L5, R1, R2, R5, L3, L4, R1, L5, R1, L4, " | |
"L3, R5, R5, L3, L4, L4, R2, R2, L5, R3, R1, R2, R5, L5, " | |
"L3, R4, L5, R5, L3, R1, L1, R4, R4, L3, R2, R5, R1, R2, " | |
"L1, R4, R1, L3, L3, L5, R2, R5, L1, L4, R3, R3, L3, R2, " | |
"L5, R1, R3, L3, R2, L1, R4, R3, L4, R5, L2, L2, R5, R1, " | |
"R2, L4, L4, L5, R3, L4") | |
distance = sum(map(abs, travel(moves))) | |
print(distance) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment