Haskell Quiz/Chess960/Solution Sjanssen

From HaskellWiki
< Haskell Quiz‎ | Chess960
Revision as of 20:02, 5 January 2007 by Sjanssen (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.


import Data.List
import System.Random
import System

bishopRule xs = even i /= even j
 where
    [i, j] = elemIndices 'B' xs

kingRule xs = i < k && k < j
 where
    [i, j] = elemIndices 'R' xs
    [k]    = elemIndices 'K' xs

white = uniq . filter kingRule . filter bishopRule . permutations $ pieces
 where
    pieces = "KQRRNNBB"

printArrangement x = do
    putStrLn x
    putStrLn . reverse $ x

main = do
    args <- getArgs
    case args of
        ["all"] -> mapM_ printArrangement white
        []      -> randomRIO (0, 959) >>= printArrangement . (white!!)

-- Utility functions:

uniq :: Ord a => [a] -> [a]
uniq = map head . group . sort

allInsertions x [] = [[x]]
allInsertions x (y:ys) = [x:y:ys] ++ map (y:) (allInsertions x ys)

permutations []     = [[]]
permutations (x:xs) = concatMap (allInsertions x) . permutations $ xs