Skip to content

Instantly share code, notes, and snippets.

@RoryDungan

RoryDungan/Knight.hs

Last active Dec 10, 2017
Embed
What would you like to do?
import Control.Monad
type KnightPos = (Int, Int)
moveKnight :: KnightPos -> [KnightPos]
moveKnight (c,r) = do
(c',r') <- [(c+2,r-1), (c+2,r+1), (c-2,r+1), (c-2,r-1)
,(c+1,r-2), (c+1,r+2), (c-1,r+2), (c-1,r-2)
]
guard (c' `elem` [1..8] && r' `elem` [1..8])
return (c', r')
in3 :: KnightPos -> [KnightPos]
in3 start = do
first <- moveKnight start
second <- moveKnight first
moveKnight second
canReachIn3 :: KnightPos -> KnightPos -> Bool
canReachIn3 start end = end `elem` in3 start
canReachInX :: Int -> KnightPos -> KnightPos -> Bool
canReachInX x start end = end `elem` inX x start
inX :: Int -> KnightPos -> [KnightPos]
inX x = foldr (<=<) return $ replicate x moveKnight
in3Path :: KnightPos -> [[KnightPos]]
in3Path start = do
first <- moveKnight start
second <- moveKnight first
third <- moveKnight second
return [first, second, third]
canReachIn3Path :: KnightPos -> KnightPos -> Maybe [KnightPos]
canReachIn3Path start end =
let paths = in3Path start
path = filter ((end ==) . last) paths
in if null path then Nothing else Just $ head path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment