Knight's tour: Difference between revisions
Content added Content deleted
(→{{header|Haskell}}: Tidied.) |
|||
Line 4,086: | Line 4,086: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
<lang Haskell> |
<lang Haskell>import Data.Bifunctor (bimap) |
||
⚫ | |||
import Data.List (minimumBy, (\\) |
import Data.List (intercalate, minimumBy, sort, (\\)) |
||
import Data.Ord (comparing) |
import Data.Ord (comparing) |
||
⚫ | |||
---------------------- 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 = |
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) -> |
|||
go (a, b) |
|||
b = |
| 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] |
|||
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 ------------------------- |
||
startPoint :: String |
|||
startPoint = "e5" |
startPoint = "e5" |
||
Line 4,130: | Line 4,136: | ||
main = |
main = |
||
printTour $ |
printTour $ |
||
algebraic |
|||
⚫ | |||
<$> knightTour |
|||
⚫ | |||
where |
where |
||
printTour [] = return () |
printTour [] = return () |