crowded-chess.cpp
Go to the documentation of this file.
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
* Mikael Lagerkvist <lagerkvist@gecode.org>
*
* Copyright:
* Christian Schulte, 2001
* Mikael Lagerkvist, 2005
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
using namespace Gecode;
const int kval[] = {
0, 0, 0, 0, 5,
9, 15, 21, 29, 37,
47, 57, 69, 81, 94,
109
};
namespace {
TupleSet bishops;
class Bishops : public Space {
public:
const int n;
BoolVarArray k;
bool valid_pos(int i, int j) {
return (i >= 0 && i < n) && (j >= 0 && j < n);
}
Bishops(int size)
: n(size), k(*this,n*n,0,1) {
Matrix<BoolVarArray> kb(k, n, n);
for (int l = n; l--; ) {
const int il = (n-1) - l;
BoolVarArgs d1(l+1), d2(l+1), d3(l+1), d4(l+1);
for (int i = 0; i <= l; ++i) {
d1[i] = kb(i+il, i);
d2[i] = kb(i, i+il);
d3[i] = kb((n-1)-i-il, i);
d4[i] = kb((n-1)-i, i+il);
}
linear(*this, d1, IRT_LQ, 1);
linear(*this, d2, IRT_LQ, 1);
linear(*this, d3, IRT_LQ, 1);
linear(*this, d4, IRT_LQ, 1);
}
linear(*this, k, IRT_EQ, 2*n - 2);
// Forced bishop placement from crowded chess model
rel(*this, kb(n-1, 0), IRT_EQ, 1);
rel(*this, kb(n-1, n-1), IRT_EQ, 1);
branch(*this, k, BOOL_VAR_DEGREE_MAX(), BOOL_VAL_MAX());
}
Bishops(Bishops& s) : Space(s), n(s.n) {
k.update(*this, s.k);
}
virtual Space* copy(void) {
return new Bishops(*this);
}
};
void init_bishops(int size) {
Bishops* prob = new Bishops(size);
DFS<Bishops> e(prob);
IntArgs ia(size*size);
delete prob;
bishops.init(size*size);
while (Bishops* s = e.next()) {
for (int i = size*size; i--; )
ia[i] = s->k[i].val();
bishops.add(ia);
delete s;
}
bishops.finalize();
}
}
class CrowdedChess : public Script {
protected:
const int n;
IntVarArray s;
IntVarArray queens,
rooks;
BoolVarArray knights;
enum
{Q,
R,
B,
K,
E,
PMAX
} piece;
// Is (i,j) a valid position on the board?
bool valid_pos(int i, int j) {
return (i >= 0 && i < n) &&
(j >= 0 && j < n);
}
void knight_constraints(void) {
static const int kmoves[4][2] = {
{-1,2}, {1,2}, {2,-1}, {2,1}
};
Matrix<BoolVarArray> kb(knights, n, n);
for (int x = n; x--; )
for (int y = n; y--; )
for (int i = 4; i--; )
if (valid_pos(x+kmoves[i][0], y+kmoves[i][1]))
rel(*this,
kb(x, y),
BOT_AND,
kb(x+kmoves[i][0], y+kmoves[i][1]),
0);
}
public:
enum {
PROP_TUPLE_SET,
PROP_DECOMPOSE
};
CrowdedChess(const SizeOptions& opt)
: Script(opt),
n(opt.size()),
s(*this, n*n, 0, PMAX-1),
queens(*this, n, 0, n-1),
rooks(*this, n, 0, n-1),
knights(*this, n*n, 0, 1) {
const int nkval = sizeof(kval)/sizeof(int);
const int nn = n*n, q = n, r = n, b = (2*n)-2,
k = n <= nkval ? kval[n-1] : kval[nkval-1];
const int e = nn - (q + r + b + k);
assert(nn == (e + q + r + b + k));
Matrix<IntVarArray> m(s, n);
// ***********************
// Basic model
// ***********************
count(*this, s, E, IRT_EQ, e, opt.ipl());
count(*this, s, Q, IRT_EQ, q, opt.ipl());
count(*this, s, R, IRT_EQ, r, opt.ipl());
count(*this, s, B, IRT_EQ, b, opt.ipl());
count(*this, s, K, IRT_EQ, k, opt.ipl());
// Collect rows and columns for handling rooks and queens
for (int i = 0; i < n; ++i) {
IntVarArgs aa = m.row(i), bb = m.col(i);
count(*this, aa, Q, IRT_EQ, 1, opt.ipl());
count(*this, bb, Q, IRT_EQ, 1, opt.ipl());
count(*this, aa, R, IRT_EQ, 1, opt.ipl());
count(*this, bb, R, IRT_EQ, 1, opt.ipl());
// Connect (queens|rooks)[i] to the row it is in
element(*this, aa, queens[i], Q, IPL_DOM);
element(*this, aa, rooks[i], R, IPL_DOM);
}
// N-queens constraints
distinct(*this, queens, IPL_DOM);
distinct(*this, IntArgs::create(n,0,1), queens, IPL_DOM);
distinct(*this, IntArgs::create(n,0,-1), queens, IPL_DOM);
// N-rooks constraints
distinct(*this, rooks, IPL_DOM);
// Collect diagonals for handling queens and bishops
for (int l = n; l--; ) {
const int il = (n-1) - l;
IntVarArgs d1(l+1), d2(l+1), d3(l+1), d4(l+1);
for (int i = 0; i <= l; ++i) {
d1[i] = m(i+il, i);
d2[i] = m(i, i+il);
d3[i] = m((n-1)-i-il, i);
d4[i] = m((n-1)-i, i+il);
}
count(*this, d1, Q, IRT_LQ, 1, opt.ipl());
count(*this, d2, Q, IRT_LQ, 1, opt.ipl());
count(*this, d3, Q, IRT_LQ, 1, opt.ipl());
count(*this, d4, Q, IRT_LQ, 1, opt.ipl());
if (opt.propagation() == PROP_DECOMPOSE) {
count(*this, d1, B, IRT_LQ, 1, opt.ipl());
count(*this, d2, B, IRT_LQ, 1, opt.ipl());
count(*this, d3, B, IRT_LQ, 1, opt.ipl());
count(*this, d4, B, IRT_LQ, 1, opt.ipl());
}
}
if (opt.propagation() == PROP_TUPLE_SET) {
IntVarArgs b(s.size());
for (int i = s.size(); i--; )
b[i] = channel(*this, expr(*this, (s[i] == B)));
extensional(*this, b, bishops, opt.ipl());
}
// Handle knigths
// Connect knigths to board
for(int i = n*n; i--; )
knights[i] = expr(*this, (s[i] == K));
knight_constraints();
// ***********************
// Redundant constraints
// ***********************
// Queens and rooks not in the same place
// Faster than going through the channelled board-connection
for (int i = n; i--; )
rel(*this, queens[i], IRT_NQ, rooks[i]);
// Place bishops in two corners (from Schimpf and Hansens solution)
// Avoids some symmetries of the problem
rel(*this, m(n-1, 0), IRT_EQ, B);
rel(*this, m(n-1, n-1), IRT_EQ, B);
// ***********************
// Branching
// ***********************
// Place each piece in turn
branch(*this, s, INT_VAR_MIN_MIN(), INT_VAL_MIN());
}
CrowdedChess(CrowdedChess& e)
: Script(e), n(e.n) {
s.update(*this, e.s);
queens.update(*this, e.queens);
rooks.update(*this, e.rooks);
knights.update(*this, e.knights);
}
virtual Space*
copy(void) {
return new CrowdedChess(*this);
}
virtual void
print(std::ostream& os) const {
Matrix<IntVarArray> m(s, n);
char names[PMAX];
names[E] = '.'; names[Q] = 'Q'; names[R] = 'R';
names[B] = 'B'; names[K] = 'K';
const char* sep = n < 8 ? "\t\t" : "\t";
for (int r = 0; r < n; ++r){
// Print main board
os << '\t';
for (int c = 0; c < n; ++c) {
if (m(r, c).assigned()) {
os << names[m(r, c).val()];
} else {
os << " ";
}
}
// Print each piece on its own
for (int p = 0; p < PMAX; ++p) {
if (p == E) continue;
os << sep;
for (int c = 0; c < n; ++c) {
if (m(r, c).assigned()) {
if (m(r, c).val() == p)
os << names[p];
else
os << names[E];
} else {
os << " ";
}
}
}
os << std::endl;
}
os << std::endl;
}
};
int
main(int argc, char* argv[]) {
SizeOptions opt("CrowdedChess");
opt.propagation(CrowdedChess::PROP_TUPLE_SET);
opt.propagation(CrowdedChess::PROP_TUPLE_SET,
"extensional",
"Use extensional propagation for bishops-placement");
opt.propagation(CrowdedChess::PROP_DECOMPOSE,
"decompose",
"Use decomposed propagation for bishops-placement");
opt.ipl(IPL_DOM);
opt.size(8);
opt.parse(argc,argv);
if (opt.size() < 5) {
std::cerr << "Error: size must be at least 5" << std::endl;
return 1;
}
init_bishops(opt.size());
Script::run<CrowdedChess,DFS,SizeOptions>(opt);
return 0;
}
// STATISTICS: example-any
CrowdedChess::main
int main(int argc, char *argv[])
Main function.
Definition crowded-chess.cpp:401
CrowdedChess::knight_constraints
void knight_constraints(void)
Post knight-constraints.
Definition crowded-chess.cpp:212
CrowdedChess::CrowdedChess
CrowdedChess(CrowdedChess &e)
Constructor for cloning e.
Definition crowded-chess.cpp:343
CrowdedChess::init_bishops
void init_bishops(int size)
Initialize bishops.
Definition crowded-chess.cpp:103
CrowdedChess::queens
IntVarArray queens
Row of queen in column x.
Definition crowded-chess.cpp:189
CrowdedChess::piece
enum CrowdedChess::@263340023323302220154063075062255036254004010355 piece
CrowdedChess::PMAX
@ PMAX
Number of pieces (including empty squares).
Definition crowded-chess.cpp:202
CrowdedChess::K
@ K
Knight.
Definition crowded-chess.cpp:200
CrowdedChess::B
@ B
Bishop.
Definition crowded-chess.cpp:199
CrowdedChess::Q
@ Q
Queen.
Definition crowded-chess.cpp:197
CrowdedChess::R
@ R
Rook.
Definition crowded-chess.cpp:198
CrowdedChess::E
@ E
Empty square.
Definition crowded-chess.cpp:201
CrowdedChess::s
IntVarArray s
The board.
Definition crowded-chess.cpp:188
CrowdedChess::print
virtual void print(std::ostream &os) const
Print solution.
Definition crowded-chess.cpp:359
CrowdedChess::PROP_DECOMPOSE
@ PROP_DECOMPOSE
Propagate bishops placement with decomposition.
Definition crowded-chess.cpp:232
CrowdedChess::PROP_TUPLE_SET
@ PROP_TUPLE_SET
Propagate bishops placement extensionally.
Definition crowded-chess.cpp:231
CrowdedChess::valid_pos
bool valid_pos(int i, int j)
Definition crowded-chess.cpp:206
CrowdedChess::CrowdedChess
CrowdedChess(const SizeOptions &opt)
The model of the problem.
Definition crowded-chess.cpp:236
CrowdedChess::rooks
IntVarArray rooks
Row of rook in column x.
Definition crowded-chess.cpp:190
CrowdedChess::bishops
TupleSet bishops
Set of valid positions for the bishops.
Definition crowded-chess.cpp:57
CrowdedChess::copy
virtual Space * copy(void)
Copy during cloning.
Definition crowded-chess.cpp:353
CrowdedChess::knights
BoolVarArray knights
True iff the corresponding place has a knight.
Definition crowded-chess.cpp:191
CrowdedChess::n
const int n
Board-size.
Definition crowded-chess.cpp:187
Gecode::BoolVarArgs
Passing Boolean variables.
Definition int.hh:712
Gecode::BoolVarArray
Boolean variable array.
Definition int.hh:808
Gecode::DFS
Depth-first search engine.
Definition search.hh:1036
Gecode::Driver::ScriptBase< Driver::IgnoreStepOption< Space > >::run
static void run(const Options &opt, Script *s=NULL)
Gecode::IntArgs
Passing integer arguments.
Definition int.hh:628
Gecode::IntArgs::create
static IntArgs create(int n, int start, int inc=1)
Allocate array with n elements such that for all .
Definition array.hpp:76
Gecode::IntVarArgs
Passing integer variables.
Definition int.hh:656
Gecode::IntVarArray
Integer variable array.
Definition int.hh:763
Gecode::Matrix
Matrix-interface for arrays.
Definition minimodel.hh:2161
Gecode::Matrix::col
Slice< A > col(int c) const
Access column c.
Definition matrix.hpp:183
Gecode::Matrix::row
Slice< A > row(int r) const
Access row r.
Definition matrix.hpp:177
Gecode::Search::Base::next
virtual T * next(void)
Return next solution (NULL, if none exists or search has been stopped).
Definition base.hpp:46
Gecode::SizeOptions
Options for scripts with additional size parameter
Definition driver.hh:675
Gecode::Space
Computation spaces.
Definition core.hpp:1742
Gecode::TupleSet
Class represeting a set of tuples.
Definition int.hh:2191
Gecode::VarArray::update
void update(Space &home, VarArray< Var > &a)
Update array to be a clone of array a.
Definition array.hpp:1013
Test::Options::parse
void parse(int argc, char *argv[])
Parse commandline arguments.
Definition test.cpp:120
kval
const int kval[]
Definition crowded-chess.cpp:46
driver.hh
int.hh
Gecode::Script
Driver::ScriptBase< Driver::IgnoreStepOption< Space > > Script
Base-class for scripts.
Definition driver.hh:801
Gecode::branch
void branch(Home home, const FloatVarArgs &x, FloatVarBranch vars, FloatValBranch vals, FloatBranchFilter bf=nullptr, FloatVarValPrint vvp=nullptr)
Branch over x with variable selection vars and value selection vals.
Definition branch.cpp:39
Gecode::linear
void linear(Home home, const FloatVarArgs &x, FloatRelType frt, FloatVal c)
Post propagator for .
Definition linear.cpp:41
Gecode::rel
void rel(Home home, FloatVar x0, FloatRelType frt, FloatVar x1)
Post propagator for .
Definition rel.cpp:68
Gecode::extensional
void extensional(Home home, const IntVarArgs &x, DFA d, IntPropLevel ipl=IPL_DEF)
Post domain consistent propagator for extensional constraint described by a DFA.
Definition extensional-regular.cpp:39
Gecode::IRT_EQ
@ IRT_EQ
Equality ( ).
Definition int.hh:926
Gecode::IRT_NQ
@ IRT_NQ
Disequality ( ).
Definition int.hh:927
Gecode::IRT_LQ
@ IRT_LQ
Less or equal ( ).
Definition int.hh:928
Gecode::BOT_AND
@ BOT_AND
Conjunction.
Definition int.hh:951
Gecode::IPL_DOM
@ IPL_DOM
Domain propagation Options: basic versus advanced propagation.
Definition int.hh:979
minimodel.hh
Gecode
Gecode toplevel namespace
Gecode::count
void count(Home home, const IntVarArgs &x, int n, IntRelType irt, int m, IntPropLevel ipl=IPL_DEF)
Post propagator for .
Definition count.cpp:40
Gecode::channel
void channel(Home home, FloatVar x0, IntVar x1)
Post propagator for channeling a float and an integer variable .
Definition channel.cpp:41
Gecode::expr
IntVar expr(Home home, const LinIntExpr &e, const IntPropLevels &ipls=IntPropLevels::def)
Post linear expression and return its value.
Definition int-expr.cpp:915
Gecode::distinct
void distinct(Home home, const IntVarArgs &x, IntPropLevel ipl=IPL_DEF)
Post propagator for for all .
Definition distinct.cpp:46
Gecode::element
void element(Home home, IntSharedArray n, IntVar x0, IntVar x1, IntPropLevel ipl=IPL_DEF)
Post domain consistent propagator for .
Definition element.cpp:39
Gecode::BOOL_VAL_MAX
BoolValBranch BOOL_VAL_MAX(void)
Select largest value.
Definition val.hpp:135
Gecode::INT_VAL_MIN
IntValBranch INT_VAL_MIN(void)
Select smallest value.
Definition val.hpp:55
Gecode::BOOL_VAR_DEGREE_MAX
BoolVarBranch BOOL_VAR_DEGREE_MAX(BranchTbl tbl=nullptr)
Select variable with largest degree.
Definition var.hpp:389
Gecode::INT_VAR_MIN_MIN
IntVarBranch INT_VAR_MIN_MIN(BranchTbl tbl=nullptr)
Select variable with smallest min.
Definition var.hpp:186