Programming Praxis – Knight Moves

In today’s Programming Praxis exercise, our goal is to list all the potential ways a knight on a chess board can get from one position to another. Let’s get started, shall we?

import Data.Ix

A knight can move to 8 positions, assuming they fit on the board. Each move is a combination of moving one square in one direction and two in the other.

moves :: (Int, Int) -> [(Int, Int)]
moves (x,y) = [(x+dx,y+dy) | [dx,dy] <- combos [[-1,1],[-2,2]]
              , inRange (1,8) (x+dx), inRange (1,8) (y+dy)]
              where combos xs = sequence xs ++ sequence (reverse xs)

To find the possible paths to the target square we simply generate all possible sequences of n moves and take the ones that end in the desired position.

paths :: (Int, Int) -> (Int, Int) -> Int -> [[(Int, Int)]]
paths from to n = map reverse . filter (\(x:_) -> x == to) $
                  iterate (>>= \(x:xs) -> map (:x:xs) $ moves x) [[from]] !! n

A test to see of everything is working properly:

main :: IO ()
main = mapM_ print $ paths (8,8) (1,1) 6

Tags: , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: