Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- this code is weak
- import Control.Applicative
- import Data.Maybe
- import Data.Char
- import qualified Data.Set as Set
- knightMoves = [(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2),(1,-2),(2,-1),(2,1)]
- type ChessSquare = (Int,Int)
- legalKnightMoves :: ChessSquare -> [ChessSquare]
- legalKnightMoves v@(r,c) = filter (\(a,b)-> (a >= 1 && b >= 1 && a <= 8 && b <= 8)) $ (\(a,b)(x,y)->((a+x),(b+y))) <$> [v] <*> knightMoves
- routeKnightPath :: [[ChessSquare]] -> Set.Set ChessSquare -> ChessSquare -> Maybe [ChessSquare]
- routeKnightPath [] _ dest = Nothing
- routeKnightPath (c:cp) visited dest =
- let mostRecent = (last c)
- (curR,curC) = (fst mostRecent, snd mostRecent)
- in if(curR, curC) == dest then
- Just c
- else
- let allMoves = legalKnightMoves (curR, curC)
- movesNotSeen = filter (\move -> not (Set.member move visited)) allMoves
- newVis = Set.union (Set.fromList movesNotSeen) visited
- fullFuturePaths = (\x-> (++[x])) <$> movesNotSeen <*> [c]
- in routeKnightPath (cp++fullFuturePaths) newVis dest
- ---------------Front End---------------
- --doRoute startingPos endingPos [forbiddenPos1 forbiddenPos2 etc.]
- --where pos = [a-h][1-8]
- doRoute xs =
- let positions = words xs
- knightLoc = fromBoard (positions !! 0)
- destination = fromBoard (positions !! 1)
- forbidden = map fromBoard (drop 2 positions)
- path = routeKnightPath [[knightLoc]] (Set.fromList forbidden) destination
- in (path >>= (return . (map toBoard)))
- fromBoard :: String -> ChessSquare
- fromBoard (x:y) = let (a,b) = unzip boardMapping
- revZip = zip b a
- in (fromJust $ lookup x revZip, (read y)::Int)
- toBoard :: ChessSquare -> String
- toBoard (a,b) = [fromJust $ lookup a boardMapping] ++ show b
- boardMapping = (zip [1..] ['a'..'h'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement