N-queens problem: Difference between revisions

Content deleted Content added
Hout (talk | contribs)
Line 5,227:
{{Trans|JavaScript}}
<lang haskell>import Data.List (transpose, intercalate)
import Data.Bool (bool)
 
queenPuzzle :: Int -> Int -> [[Int]]
Line 5,237 ⟶ 5,238:
foldr
(\iCol b ->
if safe (nRows - 1) iCol solutionbool
then b ++ [solution ++ [iCol]]
else (b ++ [solution ++ [iCol]])
(safe (nRows - 1) iCol solution))
[]
[1 .. nCols])
Line 5,246 ⟶ 5,248:
where
safe iRow iCol solution =
True(not `notElem`. or) $
zipWith
(\sc sr ->
(iCol == sc) || (sc + sr == iCol + iRow) || (sc - sr == iCol - iRow))
(sc + sr == (iCol + iRow)) || (sc - sr == (iCol - iRow)))
solution
[0 .. iRow - 1]
Line 5,256 ⟶ 5,259:
-- 10 columns of solutions for the 7*7 board:
showSolutions :: Int -> Int -> [String]
showSolutions nCols nBoardSizenSize =
unlines <$>
((fmap (intercalate " " <$>) . transpose . (fmap boardLines <$>)) <$>
chunksOf nCols (queenPuzzle nBoardSizenSize nBoardSizenSize))
where
boardLines rows =
(\r -> (bool '.' '♛' . (== r)) <$> [1 .. (length rows)]) <$> rows
(\r ->
foldMap
(\c ->
[ if r == c
then '♛'
else '.'
])
[1 .. (length rows)]) <$>
rows
 
chunksOf :: Int -> [a] -> [[a]]
Line 5,312 ⟶ 5,307:
..♛.... ..♛.... ...♛... ..♛.... ♛...... .....♛. ...♛... .♛..... ......♛ ....♛..
.....♛. .....♛. .....♛. .....♛. ....♛.. ...♛... .....♛. ....♛.. ...♛... ..♛....</pre>
 
 
===Breadth-first search and Depth-first search===