Knight's tour: Difference between revisions

Line 4,086:
 
=={{header|Haskell}}==
<lang Haskell>{-#import LANGUAGEData.Bifunctor TupleSections #-}(bimap)
import Data.Char (ordchr, chrord)
 
import Data.List (intercalate, minimumBy, sort, (\\), intercalate, sort)
import Data.Ord (comparing)
 
import Data.Char (ord, chr)
---------------------- KNIGHT'S TOUR ---------------------
import Data.Bool (bool)
 
type Square = (Int, Int)
Line 4,100:
| otherwise = knightTour $ newSquare : moves
where
newSquare = minimumBy (comparing (length . findMoves)) possibilities
minimumBy
(comparing (length . findMoves))
possibilities
possibilities = findMoves $ head moves
findMoves = (\\ moves) . knightOptions
Line 4,106 ⟶ 4,109:
knightOptions :: Square -> [Square]
knightOptions (x, y) =
knightMoves >>= go . bimap (+ x) (+ y)
where
(\(i, j) ->
go let (a, = x + ib)
| onBoard a && onBoard b = y[(a, + jb)]
| otherwise = []
in bool [] [(a, b)] (onBoard a && onBoard b))
 
knightMoves :: [(Int, Int)]
knightMoves = (deltas >>=) . go =<< deltas
where
let deltas = [id, negate] <*> [1, 2]
in deltas >>= [id, negate] <*> [1, 2]
go i x
(\i -> deltas >>= (bool [] . return . (i, )) <*> ((abs i /=) . abs))
| abs i /= abs x = [(i, x)]
| otherwise = []
 
onBoard :: Int -> Bool
onBoard = (&&) . (0 <) <*> (9 >)
 
-- TEST -------------------------- TEST -------------------------
startPoint :: String
startPoint = "e5"
 
Line 4,130 ⟶ 4,136:
main =
printTour $
algebraic
algebraic <$> knightTour [(\[x, y] -> (ord x - 96, ord y - 48)) startPoint]
<$> knightTour
algebraic <$> knightTour [(\[x, y] -> (ord x - 96, ord y - 48)) startPoint]
where
printTour [] = return ()
9,655

edits