{- queens9.out, as produced by this program, is 32032 bytes -}
main = writeQueens 9
writeQueens n = writeFile fn (show (queens n))
where
fn = "queens" ++ show n ++ ".out"
newtype Queens = Queens [[Int]]
instance Show Queens where
show (Queens qs) = concatMap showBoard qs
showBoard board = concatMap showRow board ++ "\n"
where
size = length board
dots = replicate size '.'
showRow n = take (n - 1) dots ++ "X" ++ take (size - n) dots ++ "\n"
queens b = Queens (queens' b)
where
queens' 0 = [[]]
queens' n = [ p ++ [n] | p <- queens' (n - 1), n <- [1..b], safe p n ]
safe p n = and [ not (check (i, j) (m, n)) | (i, j) <- zip [1 .. l] p]
where l = length p; m = l + 1
check (i, j) (m, n) = j == n || i + j == m + n || i - j == m - n