Created
March 26, 2016 09:52
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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