Skip to content

Instantly share code, notes, and snippets.

@jakab922
Last active February 5, 2016 14:40
Show Gist options
  • Save jakab922/2106f259be734bc1f10c to your computer and use it in GitHub Desktop.
Save jakab922/2106f259be734bc1f10c to your computer and use it in GitHub Desktop.
The in_n function is important which calculates the reachable squares reachable in n steps on the chessboard(quite inefficient though)
import Data.List (nub)
class Monad m => MonadPlus m where
mzero :: m a
mplus :: m a -> m a -> m a
instance MonadPlus [] where
mzero = []
mplus = (++)
guard :: (MonadPlus m) => Bool -> m ()
guard True = return ()
guard False = mzero
type KnightPos = (Integer, Integer)
moveKnight :: KnightPos -> [KnightPos]
moveKnight (c, r) = do
(c', r') <- [(c + dc, r + dr) | dc <- [-2..2], dr <- [-2..2], abs(dc) + abs(dr) == 3]
guard (c' `elem` [1..8] && r' `elem` [1..8])
return (c', r')
in_3 :: KnightPos -> [KnightPos]
in_3 start = do
first <- moveKnight start
second <- moveKnight first
moveKnight second
in_n :: Int -> KnightPos -> [KnightPos]
in_n n pos = foldr (\f x -> f x) [pos] $ take n $ repeat $ nub . (>>= moveKnight)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment