Skip to content

Instantly share code, notes, and snippets.

@sean-clayton
Last active April 28, 2019 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sean-clayton/486e39193821cfaf61b2d15c19edce3e to your computer and use it in GitHub Desktop.
Save sean-clayton/486e39193821cfaf61b2d15c19edce3e to your computer and use it in GitHub Desktop.
-- Eight queens solution in 5 lines of haskell
solution :: [Int]
solution = head (allSolutions !! 8)
allSolutions :: [[[Int]]]
allSolutions = iterate (concatMap extendSolution) [[]]
extendSolution :: [Int] -> [[Int]]
extendSolution qs = map (:qs) $ filter (`okToAdd` qs) [0..7]
okToAdd :: Int -> [Int] -> Bool
okToAdd q qs = all (okToAddGivenDir q qs) [ succ, pred, id ]
okToAddGivenDir :: Int -> [Int] -> (Int -> Int) -> Bool
okToAddGivenDir q0 qs f = and $ zipWith (/=) (tail $ iterate f q0) qs
main = do
putStrLn (show solution)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment