MiniZinc is a high level Constraint Programming (CP) language (or a frontend for constraint programming solvers). Being distributed with its own IDE, it is a most friendly enviornment to have a taste on what constraint programming is. Here is the n-Queens problem, which is like a hello world for CP, in MiniZinc.
include "globals.mzn"; int: n; % fixed integer parameter % (xs[y],y), is a coordiate for a queen array[1..n] of var 1..n: xs; % constraint for the n queens problem on nxn borard constraint alldifferent(xs); constraint forall (i,j in 1..n where i<j) ( j-i != abs(xs[i]-xs[j]) ); solve satisfy; % find satisfying solution output ["Solution:\n", "xs = \(xs) \n", "To pretty-print the chessboard config, use ghci to run:\n", "let xs = \(xs) in putStrLn $ concat $ Data.List.intersperse \"\\n\" [ [if i==k then 'Q' else '#' | k <- ys ] | i<-[1..length xs] ]"];
Note that fixed parameters, which should be initialized before runnning the solver, are declared witout the
var keyword and the variables that are to be searched for solutions are declared with the
var keyword. This
var is in fact part of the type.
And in the IDE it looks like this.
Since we have not initizlied the fixed paramenter
n, the IDE will prompt for its value when you run it with Ctrl-R.
The output looks like this for
n = 8.
xs = [3, 6, 4, 2, 8, 5, 7, 1]
To pretty-print the chessboard config, use ghci to run:
let xs = [3, 6, 4, 2, 8, 5, 7, 1] in putStrLn $ concat $ Data.List.intersperse "\n" [ [if i==k then 'Q' else '#' | k <- ys ] | i<-[1..length xs] ]
Try to pretty-print the result in 2D chessboard configuration using your favorite programming langauge, which is in my case Haskell.
Seems like MiniZinc got a correct solution :)
You actually have to use an external mechanism to print this last step because you cannot use var types where normal types are required.
var int is differet from
output command only prints
var strings. Var is like a stage annotation that contaminates the result once you use it. For instance if you try to print out something that relies on any
var value MiniZinc will complain that it is
var string not
string. If a high level constraint programming lanaguage supported multi-staged computation we could actualy do those kind of things at the last step of printing out a result depending on the solution value.