Created
July 30, 2009 09:41
-
-
Save sebfisch/158635 to your computer and use it in GitHub Desktop.
Efficient solver for the n-queens problem in Curry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Efficient solver for the n-queens problem in Curry. | |
-- | |
-- A placement is represented as permutation of [1..n], each list | |
-- element represents the placement of a queen in the column | |
-- corresponding to its index. | |
-- The implementation uses a finite domain constraint solver which is | |
-- available in the Curry system PAKCS. | |
-- | |
import CLPFD | |
-- A placement of n queens must consist of distinct numbers between 1 | |
-- and n such that no queens capture each other diagonally. | |
-- | |
queens :: Int -> [Int] | |
queens n | domain qs 1 n & all_different qs & safe qs | |
& labeling [FirstFailConstrained] qs | |
= qs | |
where qs = [ unknown | _ <- [1..n] ] | |
-- As queens are placed in different rows and columns automatically, | |
-- we only check that they don't capture each other diagonally. | |
-- | |
safe :: [Int] -> Success | |
safe qs = andC [ (j-i) /=# (q_j-#q_i) & (j-i) /=# (q_i-#q_j) | |
| (i,q_i) <- iqs, (j,q_j) <- iqs, i < j ] | |
where iqs = zip [1..] qs | |
-- The safe predicate uses an auxiliary predicate for constraint | |
-- conjunction. | |
-- | |
andC :: [Success] -> Success | |
andC = foldr (&) success |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment