Skip to content

Instantly share code, notes, and snippets.

@BenBals
Created March 26, 2016 09:52
Show Gist options
  • Save BenBals/edf219e8563397714d28 to your computer and use it in GitHub Desktop.
Save BenBals/edf219e8563397714d28 to your computer and use it in GitHub Desktop.
Make a function that checks whether a knight can reach a certain position on a chess board from a given starting position within 3 moves. Position denoted as (Int,Int)
import qualified Control.Monad as M
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)
]
M.guard (c' `elem` [1..8] && r' `elem` [1..8])
return (c',r')
canReachIn3 :: KnightPos -> KnightPos -> Bool
canReachIn3 start target = target `elem` in3 start
@BenBals
Copy link
Author

BenBals commented Mar 26, 2016

Can your programming language do this in 14 lines. Note that this isn't code golf code. This is the readable version with (optional) type annotations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment