Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. this code is weak
  2.  
  3. import Control.Applicative
  4.  
  5. import Data.Maybe
  6.  
  7. import Data.Char
  8.  
  9. import qualified Data.Set as Set
  10.  
  11. knightMoves = [(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2),(1,-2),(2,-1),(2,1)]
  12.  
  13. type ChessSquare = (Int,Int)
  14.  
  15. legalKnightMoves :: ChessSquare -> [ChessSquare]
  16.  
  17. 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
  18.  
  19. routeKnightPath :: [[ChessSquare]] -> Set.Set ChessSquare -> ChessSquare -> Maybe [ChessSquare]
  20.  
  21. routeKnightPath [] _ dest = Nothing
  22.  
  23. routeKnightPath (c:cp) visited dest =
  24.  
  25.   let mostRecent = (last c)
  26.  
  27.       (curR,curC) = (fst mostRecent, snd mostRecent)
  28.  
  29.       in if(curR, curC) == dest then
  30.  
  31.            Just c
  32.  
  33.          else
  34.  
  35.            let allMoves = legalKnightMoves (curR, curC)
  36.  
  37.                movesNotSeen = filter (\move -> not (Set.member move visited)) allMoves
  38.  
  39.                newVis = Set.union (Set.fromList movesNotSeen) visited
  40.  
  41.                fullFuturePaths = (\x-> (++[x])) <$> movesNotSeen <*> [c]
  42.  
  43.            in routeKnightPath (cp++fullFuturePaths) newVis dest
  44.  
  45.              
  46.  
  47. ---------------Front End---------------
  48.  
  49. --doRoute startingPos endingPos [forbiddenPos1 forbiddenPos2 etc.]
  50.  
  51. --where pos = [a-h][1-8]
  52.  
  53. doRoute xs =
  54.  
  55.   let positions = words xs
  56.  
  57.       knightLoc = fromBoard (positions !! 0)
  58.  
  59.       destination = fromBoard (positions !! 1)
  60.  
  61.       forbidden = map fromBoard (drop 2 positions)
  62.  
  63.       path = routeKnightPath [[knightLoc]] (Set.fromList forbidden) destination
  64.  
  65.       in (path >>= (return . (map toBoard)))
  66.  
  67.        
  68.  
  69. fromBoard :: String -> ChessSquare
  70.  
  71. fromBoard (x:y) = let (a,b) = unzip boardMapping
  72.  
  73.                       revZip = zip b a
  74.  
  75.                   in (fromJust $ lookup x revZip, (read y)::Int)
  76.  
  77. toBoard :: ChessSquare -> String
  78.  
  79. toBoard (a,b) =  [fromJust $ lookup a boardMapping] ++ show b
  80.  
  81.  
  82.  
  83. boardMapping = (zip [1..] ['a'..'h'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement