I wrote a function that takes as input a vector with two integers between 1
and 8
representing a position in a chessboard and that should output a vector where each cell is a similar vector of integers, with the positions that a knight in the input position could reach.
E.g. for the input 1 1
, my function should output [2 3] [3 2]
(I'm using the []
to represent the boxes of the cells).
This is what I wrote:
knight_moves ← {
⍝ Monadic function, expects a vector with 2 integers
⍝ Given a chessboard position, find the legal knight moves
signs ← , ∘.,⍨(¯1 1)
offsets ← ((⊂⌽),⊂) 2 1
moves ← , signs ∘.× offsets
locations ← moves + ⊂⍵
valid ← ^/¨(1∘≤∧≤∘8) locations
valid/locations
}
This works and gives the expected result for a series of test cases. Since I am quite new to APL, I wanted to know what could be written in a cleaner way.
This question has been followed-up here.