Knight's tour: Difference between revisions

Content added Content deleted
Line 4,086: Line 4,086:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>{-# LANGUAGE TupleSections #-}
<lang Haskell>import Data.Bifunctor (bimap)
import Data.Char (chr, ord)

import Data.List (minimumBy, (\\), intercalate, sort)
import Data.List (intercalate, minimumBy, sort, (\\))
import Data.Ord (comparing)
import Data.Ord (comparing)

import Data.Char (ord, chr)
---------------------- KNIGHT'S TOUR ---------------------
import Data.Bool (bool)


type Square = (Int, Int)
type Square = (Int, Int)
Line 4,100: Line 4,100:
| otherwise = knightTour $ newSquare : moves
| otherwise = knightTour $ newSquare : moves
where
where
newSquare = minimumBy (comparing (length . findMoves)) possibilities
newSquare =
minimumBy
(comparing (length . findMoves))
possibilities
possibilities = findMoves $ head moves
possibilities = findMoves $ head moves
findMoves = (\\ moves) . knightOptions
findMoves = (\\ moves) . knightOptions
Line 4,106: Line 4,109:
knightOptions :: Square -> [Square]
knightOptions :: Square -> [Square]
knightOptions (x, y) =
knightOptions (x, y) =
knightMoves >>=
knightMoves >>= go . bimap (+ x) (+ y)
where
(\(i, j) ->
let a = x + i
go (a, b)
b = y + j
| onBoard a && onBoard b = [(a, b)]
| otherwise = []
in bool [] [(a, b)] (onBoard a && onBoard b))


knightMoves :: [(Int, Int)]
knightMoves :: [(Int, Int)]
knightMoves =
knightMoves = (deltas >>=) . go =<< deltas
where
let deltas = [id, negate] <*> [1, 2]
in deltas >>=
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 :: Int -> Bool
onBoard = (&&) . (0 <) <*> (9 >)
onBoard = (&&) . (0 <) <*> (9 >)


-- TEST ---------------------------------------------------
--------------------------- TEST -------------------------
startPoint :: String
startPoint = "e5"
startPoint = "e5"


Line 4,130: Line 4,136:
main =
main =
printTour $
printTour $
algebraic
algebraic <$> knightTour [(\[x, y] -> (ord x - 96, ord y - 48)) startPoint]
<$> knightTour
[(\[x, y] -> (ord x - 96, ord y - 48)) startPoint]
where
where
printTour [] = return ()
printTour [] = return ()