examples/queens.mod
author Alpar Juttner <alpar@cs.elte.hu>
Sun, 05 Dec 2010 17:35:23 +0100
changeset 2 4c8956a7bdf4
permissions -rw-r--r--
Set up CMAKE build environment
alpar@1
     1
/* QUEENS, a classic combinatorial optimization problem */
alpar@1
     2
alpar@1
     3
/* Written in GNU MathProg by Andrew Makhorin <mao@gnu.org> */
alpar@1
     4
alpar@1
     5
/* The Queens Problem is to place as many queens as possible on the 8x8
alpar@1
     6
   (or more generally, nxn) chess board in a way that they do not fight
alpar@1
     7
   each other. This problem is probably as old as the chess game itself,
alpar@1
     8
   and thus its origin is not known, but it is known that Gauss studied
alpar@1
     9
   this problem. */
alpar@1
    10
alpar@1
    11
param n, integer, > 0, default 8;
alpar@1
    12
/* size of the chess board */
alpar@1
    13
alpar@1
    14
var x{1..n, 1..n}, binary;
alpar@1
    15
/* x[i,j] = 1 means that a queen is placed in square [i,j] */
alpar@1
    16
alpar@1
    17
s.t. a{i in 1..n}: sum{j in 1..n} x[i,j] <= 1;
alpar@1
    18
/* at most one queen can be placed in each row */
alpar@1
    19
alpar@1
    20
s.t. b{j in 1..n}: sum{i in 1..n} x[i,j] <= 1;
alpar@1
    21
/* at most one queen can be placed in each column */
alpar@1
    22
alpar@1
    23
s.t. c{k in 2-n..n-2}: sum{i in 1..n, j in 1..n: i-j == k} x[i,j] <= 1;
alpar@1
    24
/* at most one queen can be placed in each "\"-diagonal */
alpar@1
    25
alpar@1
    26
s.t. d{k in 3..n+n-1}: sum{i in 1..n, j in 1..n: i+j == k} x[i,j] <= 1;
alpar@1
    27
/* at most one queen can be placed in each "/"-diagonal */
alpar@1
    28
alpar@1
    29
maximize obj: sum{i in 1..n, j in 1..n} x[i,j];
alpar@1
    30
/* objective is to place as many queens as possible */
alpar@1
    31
alpar@1
    32
/* solve the problem */
alpar@1
    33
solve;
alpar@1
    34
alpar@1
    35
/* and print its optimal solution */
alpar@1
    36
for {i in 1..n}
alpar@1
    37
{  for {j in 1..n} printf " %s", if x[i,j] then "Q" else ".";
alpar@1
    38
   printf("\n");
alpar@1
    39
}
alpar@1
    40
alpar@1
    41
end;