Knight's tour: Difference between revisions
Content added Content deleted
No edit summary |
(→{{header|Haskell}}: Applied hlint and hindent – slightly simplified the type of the input, and slightly uncluttered the main :: IO() function) |
||
Line 3,031: | Line 3,031: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
<lang Haskell> |
<lang Haskell>import Data.Char (ord, chr) |
||
import System (getArgs) |
|||
import Data.Char (ord, chr) |
|||
⚫ | |||
import Data.Ord (comparing) |
import Data.Ord (comparing) |
||
⚫ | |||
type Square = (Int, Int) |
type Square = (Int, Int) |
||
board :: [Square] |
board :: [Square] |
||
board = |
|||
board = [ (x,y) | x <- [1..8], y <- [1..8] ] |
|||
[ (x, y) |
|||
| x <- [1 .. 8] |
|||
, y <- [1 .. 8] ] |
|||
knightMoves :: Square -> [Square] |
knightMoves :: Square -> [Square] |
||
knightMoves (x,y) = filter ( |
knightMoves (x, y) = filter (`elem` board) jumps |
||
where |
|||
where jumps = [ (x+i,y+j) | i <- jv, j <- jv, abs i /= abs j ] |
|||
jumps = |
|||
[ (x + i, y + j) |
|||
| i <- jv |
|||
, j <- jv |
|||
, abs i /= abs j ] |
|||
jv = [1, -1, 2, -2] |
|||
knightTour :: [Square] -> [Square] |
knightTour :: [Square] -> [Square] |
||
knightTour moves |
knightTour moves |
||
| null candMoves = reverse moves |
|||
| otherwise = knightTour $ newSquare : moves |
|||
where |
|||
where newSquare = minimumBy (comparing (length . findMoves)) candMoves |
|||
newSquare = minimumBy (comparing (length . findMoves)) candMoves |
|||
candMoves = findMoves $ head moves |
|||
findMoves = (\\ moves) . knightMoves |
|||
toSq :: String -> (Int, Int) |
|||
⚫ | |||
⚫ | |||
sq <- fmap (toSq . head) getArgs |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
</lang> |
|||
toAlg :: (Int, Int) -> String |
|||
Output: |
|||
⚫ | |||
<pre> |
|||
⚫ | |||
-- TEST ----------------------------------------------------------------------- |
|||
sq :: (Int, Int) |
|||
sq = toSq "e5" -- Input: starting position on the bord, e.g. (5, 5) as "e5" |
|||
⚫ | |||
⚫ | |||
where |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
{{Out}} |
|||
⚫ | |||
g1 -> h3 -> g5 -> h7 -> f8 -> d7 -> b8 -> a6 |
g1 -> h3 -> g5 -> h7 -> f8 -> d7 -> b8 -> a6 |
||
b4 -> a2 -> c1 -> d3 -> b2 -> a4 -> b6 -> a8 |
b4 -> a2 -> c1 -> d3 -> b2 -> a4 -> b6 -> a8 |
||
Line 3,076: | Line 3,087: | ||
a5 -> c6 -> a7 -> c8 -> d6 -> b5 -> d4 -> e2 |
a5 -> c6 -> a7 -> c8 -> d6 -> b5 -> d4 -> e2 |
||
c3 -> d1 -> f2 -> h1 -> g3 -> e4 -> f6 -> g8 |
c3 -> d1 -> f2 -> h1 -> g3 -> e4 -> f6 -> g8 |
||
h6 -> g4 -> h2 -> f1 -> e3 -> f5 -> e7 -> d5 |
h6 -> g4 -> h2 -> f1 -> e3 -> f5 -> e7 -> d5</pre> |
||
</pre> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |