Skip to content

Instantly share code, notes, and snippets.

@shawa
Last active March 25, 2020 18:00
Show Gist options
  • Save shawa/f520aa207956db50694f36d84d7bafaa to your computer and use it in GitHub Desktop.
Save shawa/f520aa207956db50694f36d84d7bafaa to your computer and use it in GitHub Desktop.
Attempt at solving Katas with Linear Algebra in APL, dear me
⍝ A rotation matrix, rotates coordinates ⍵ rads
rotate ← {3 3⍴((2○⍵)(-1○⍵)0(1○⍵)(2○⍵)0 0 0 1)}
⍝ A translation matrix, displaces coordinates ⍵
⍝ steps downward (moves us ⍵ steps north)
translate ← {3 3⍴(1 0(-⍵)0 1 0 0 0 1)}
⍝ Lookup function to convert 'L' and 'R' to
⍝ rotation angles
pi ← ○1
angle ← {('LR'⍳⍵)⊃((pi÷2)((3×pi)÷2))}
⍝ Modifed verson of John's split function[1], to take
⍝ a string of form 'L1, R3, R4" and convert it to
⍝ a vector of ('L1' 'R3' 'R4')
⍝ [1] http://dfns.dyalog.com/n_santa.htm
split ← {((0,⍵∊',')⊂',',⍵)~¨⊂',',' '}
⍝ Compose a rotation and translation, computed from
⍝ An instruction (('L' 20, R5 etc.) into a single-step
⍝ Transformation
mkTransform ← {(rotate angle 1⊃⍵)+.×(translate⍎1↓⍵)}
⍝ Interpret a set of instructions and reduce to
⍝ a single transformation
interpret ← {⊃+.×/mkTransform¨ split ⍵}
⍝ Starting at (0 0), perform compound translation
⍝ and return finishing coordinates
follow ← {2↑∊(interpret ⍵)+.×(3 1⍴0 0 1)}
⍝ Compute taxicab distance of an (x y) vector
taxi ← {⌈+/|¨⍵}
solve ← {taxi follow ⍵}
⍝ Example run
example ← 'R5, L5, R5, R3'
solve example
7
⍝ Of course, we can also be cruel:
solve_2 ← {{⌈+/|¨⍵}{2↑∊({⊃+.×/{({3 3⍴((2○⍵)(-1○⍵)0(1○⍵)(2○⍵)0 0 0 1)}{('LR'⍳⍵)⊃((pi÷2)((3×pi)÷2))}1⊃⍵)+.×({3 3⍴(1 0(-⍵)0 1 0 0 0 1)}⍎1↓⍵)}¨{((0,⍵∊',')⊂',',⍵)~¨⊂',',' '}⍵}⍵)+.×(3 1⍴0 0 1)}⍵}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment