Generated on Thu Apr 5 2018 19:44:19 for Gecode by doxygen 1.8.13
queen-armies.cpp
Go to the documentation of this file.
1 /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
2 /*
3  * Main authors:
4  * Mikael Lagerkvist <lagerkvist@gecode.org>
5  *
6  * Copyright:
7  * Mikael Lagerkvist, 2006
8  *
9  * Last modified:
10  * $Date$ by $Author$
11  * $Revision$
12  *
13  * This file is part of Gecode, the generic constraint
14  * development environment:
15  * http://www.gecode.org
16  *
17  * Permission is hereby granted, free of charge, to any person obtaining
18  * a copy of this software and associated documentation files (the
19  * "Software"), to deal in the Software without restriction, including
20  * without limitation the rights to use, copy, modify, merge, publish,
21  * distribute, sublicense, and/or sell copies of the Software, and to
22  * permit persons to whom the Software is furnished to do so, subject to
23  * the following conditions:
24  *
25  * The above copyright notice and this permission notice shall be
26  * included in all copies or substantial portions of the Software.
27  *
28  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
31  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
32  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
33  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
34  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35  *
36  */
37 
38 
39 #include <gecode/driver.hh>
40 #include <gecode/int.hh>
41 #include <gecode/minimodel.hh>
42 #include <gecode/set.hh>
43 
44 using namespace Gecode;
45 
51 
72 public:
73  const int n;
74  SetVar U,
75  W;
77  b;
79 
81  enum {
83  BRANCH_SPECIFIC
84  };
85 
88  IntMaximizeScript(opt),
89  n(opt.size()),
90  U(*this, IntSet::empty, IntSet(0, n*n)),
91  W(*this, IntSet::empty, IntSet(0, n*n)),
92  w(*this, n*n, 0, 1),
93  b(*this, n*n, 0, 1),
94  q(*this, 0, n*n)
95  {
96  // Basic rules of the model
97  for (int i = n*n; i--; ) {
98  // w[i] means that no blacks are allowed on A[i]
99  rel(*this, w[i] == (U || A[i]));
100  // Make sure blacks and whites are disjoint.
101  rel(*this, !w[i] || !b[i]);
102  // If i in U, then b[i] has a piece.
103  rel(*this, b[i] == (singleton(i) <= U));
104  }
105 
106  // Connect optimization variable to number of pieces
107  linear(*this, w, IRT_EQ, q);
108  linear(*this, b, IRT_GQ, q);
109 
110  // Connect cardinality of U to the number of black pieces.
111  IntVar unknowns = expr(*this, cardinality(U));
112  rel(*this, q <= unknowns);
113  linear(*this, b, IRT_EQ, unknowns);
114 
115  if (opt.branching() == BRANCH_NAIVE) {
116  branch(*this, w, BOOL_VAR_NONE(), BOOL_VAL_MAX());
117  branch(*this, b, BOOL_VAR_NONE(), BOOL_VAL_MAX());
118  } else {
119  QueenBranch::post(*this);
120  assign(*this, b, BOOL_ASSIGN_MAX());
121  }
122  }
125  : IntMaximizeScript(s), n(s.n) {
126  U.update(*this, s.U);
127  W.update(*this, s.W);
128  w.update(*this, s.w);
129  b.update(*this, s.b);
130  q.update(*this, s.q);
131  }
133  virtual Space*
134  copy(void) {
135  return new QueenArmies(*this);
136  }
138  virtual IntVar cost(void) const {
139  return q;
140  }
142  virtual void
143  print(std::ostream& os) const {
144  os << '\t';
145  for (int i = 0; i < n*n; ++i) {
146  if (w[i].assigned() && w[i].val()) os << "W";
147  else if (b[i].assigned() && b[i].val()) os << "B";
148  else if (!w[i].assigned() && !b[i].assigned()) os << " ";
149  else os << ".";
150  if ((i+1)%n == 0) os << std::endl << (i!=(n*n-1)?"\t":"");
151  }
152  os << "Number of white queens: " << q << std::endl << std::endl;
153  }
154 
162  class QueenBranch : public Brancher {
163  private:
165  mutable int start;
167  class Choice : public Gecode::Choice {
168  public:
170  int pos;
172  bool val;
176  Choice(const Brancher& b, int pos0, bool val0)
177  : Gecode::Choice(b,2), pos(pos0), val(val0) {}
179  virtual void archive(Archive& e) const {
181  e << pos << val;
182  }
183  };
184 
186  QueenBranch(Home home)
187  : Brancher(home), start(0) {}
189  QueenBranch(Space& home, QueenBranch& b)
190  : Brancher(home, b), start(b.start) {}
191 
192  public:
194  virtual bool status(const Space& home) const {
195  const QueenArmies& q = static_cast<const QueenArmies&>(home);
196  for (int i = start; i < q.n*q.n; ++i)
197  if (!q.w[i].assigned()) {
198  start = i;
199  return true;
200  }
201  // No non-assigned orders left
202  return false;
203  }
205  virtual Gecode::Choice* choice(Space& home) {
206  const QueenArmies& q = static_cast<const QueenArmies&>(home);
207  int maxsize = -1;
208  int pos = -1;
209 
210  for (int i = start; i < q.n*q.n; ++i) {
211  if (q.w[i].assigned()) continue;
212  IntSetRanges ai(A[i]);
213  SetVarUnknownRanges qU(q.U);
215  int size = Iter::Ranges::size(r);
216  if (size > maxsize) {
217  maxsize = size;
218  pos = i;
219  }
220  }
221 
222  assert(pos != -1);
223  return new Choice(*this, pos, true);
224  }
226  virtual Choice* choice(const Space&, Archive& e) {
227  int pos, val;
228  e >> pos >> val;
229  return new Choice(*this, pos, val);
230  }
234  virtual ExecStatus commit(Space& home, const Gecode::Choice& _c,
235  unsigned int a) {
236  QueenArmies& q = static_cast<QueenArmies&>(home);
237  const Choice& c = static_cast<const Choice&>(_c);
238  bool val = (a == 0) ? c.val : !c.val;
239  return me_failed(Int::BoolView(q.w[c.pos]).eq(q, val))
240  ? ES_FAILED
241  : ES_OK;
242  }
244  virtual void print(const Space&, const Gecode::Choice& _c,
245  unsigned int a,
246  std::ostream& o) const {
247  const Choice& c = static_cast<const Choice&>(_c);
248  bool val = (a == 0) ? c.val : !c.val;
249  o << "w[" << c.pos << "] = " << val;
250  }
252  virtual Actor* copy(Space& home) {
253  return new (home) QueenBranch(home, *this);
254  }
256  static void post(QueenArmies& home) {
257  (void) new (home) QueenBranch(home);
258  }
260  virtual size_t dispose(Space&) {
261  return sizeof(*this);
262  }
263  };
264 };
265 
270 int pos(int i, int j, int n) {
271  return i*n + j;
272 }
273 
277 int
278 main(int argc, char* argv[]) {
279  SizeOptions opt("QueenArmies");
280  opt.size(6);
282  opt.branching(QueenArmies::BRANCH_NAIVE, "naive");
283  opt.branching(QueenArmies::BRANCH_SPECIFIC, "specific");
284  opt.solutions(0);
285  opt.parse(argc,argv);
286 
287  // Set up the A-sets
288  // A[i] will contain the values attacked by a queen at position i
289  int n = opt.size();
290  A = new IntSet[n*n];
291  int *p = new int[std::max(n*n, 25)];
292  int pn = 0;
293  for (int i = n; i--; ) {
294  for (int j = n; j--; ) {
295  int dir[][2] = {
296  { 0, 1},
297  { 1, 1},
298  { 1, 0},
299  { 0, -1},
300  {-1, -1},
301  {-1, 0},
302  { 1, -1},
303  {-1, 1}
304  };
305  p[pn++] = pos(i, j, n);
306  for (int k = 8; k--; ) {
307  for (int l = 0; l < n
308  && 0 <= (i+l*dir[k][0]) && (i+l*dir[k][0]) < n
309  && 0 <= (j+l*dir[k][1]) && (j+l*dir[k][1]) < n; ++l) {
310  p[pn++] = pos(i+l*dir[k][0], j+l*dir[k][1], n);
311  }
312  }
313 
314  A[pos(i, j, n)] = IntSet(p, pn);
315 
316  pn = 0;
317  }
318  }
319  delete [] p;
320 
321  IntMaximizeScript::run<QueenArmies,BAB,SizeOptions>(opt);
322  return 0;
323 }
324 
325 // STATISTICS: example-any
virtual Gecode::Choice * choice(Space &home)
Return choice.
void size(unsigned int s)
Set default size.
Definition: options.hpp:590
SetExpr singleton(const LinIntExpr &e)
Singleton expression.
Definition: set-expr.cpp:694
Options for scripts with additional size parameter
Definition: driver.hh:679
BoolVarBranch BOOL_VAR_NONE(void)
Select first unassigned variable.
Definition: var.hpp:368
NNF * l
Left subtree.
Definition: bool-expr.cpp:244
void post(Home home, Term *t, int n, FloatRelType frt, FloatVal c)
Post propagator for linear constraint over floats.
Definition: post.cpp:242
Range iterator for integer sets.
Definition: int.hh:272
void branch(Home home, const FloatVarArgs &x, FloatVarBranch vars, FloatValBranch vals, FloatBranchFilter bf, FloatVarValPrint vvp)
Branch over x with variable selection vars and value selection vals.
Definition: branch.cpp:43
const FloatNum max
Largest allowed float value.
Definition: float.hh:848
virtual Choice * choice(const Space &, Archive &e)
Return choice.
IntVar q
The number of white queens placed.
void update(Space &home, VarArray< Var > &a)
Update array to be a clone of array a.
Definition: array.hpp:1060
int main(int argc, char *argv[])
Main-function.
SetVar W
Set of squares occupied by white queens.
void parse(int &argc, char *argv[])
Parse options from arguments argv (number is argc)
Definition: options.cpp:670
bool assigned(void) const
Test if all variables are assigned.
Definition: array.hpp:1073
bool pos(const View &x)
Test whether x is postive.
Definition: mult.hpp:45
virtual ExecStatus commit(Space &home, const Gecode::Choice &_c, unsigned int a)
Perform commit for choice _c and alternative a.
void linear(Home home, const FloatVarArgs &x, FloatRelType frt, FloatVal c)
Post propagator for .
Definition: linear.cpp:45
Multi _c(Gecode::IntArgs(3, 1, 2, 3))
int pos(int i, int j, int n)
Position of a piece in a square board.
Choose variables left to right.
BoolVarArray w
The placement of the white queens.
BoolAssign BOOL_ASSIGN_MAX(void)
Select largest value.
Definition: assign.hpp:109
virtual void print(const Space &, const Gecode::Choice &_c, unsigned int a, std::ostream &o) const
Print explanation.
QueenArmies(const SizeOptions &opt)
Constructor.
virtual bool status(const Space &home) const
Check status of brancher, return true if alternatives left.
Computation spaces.
Definition: core.hpp:1668
Greater or equal ( )
Definition: int.hh:909
Parametric base-class for scripts.
Definition: driver.hh:733
Base-class for both propagators and branchers.
Definition: core.hpp:620
ModEvent eq(Space &home, int n)
Restrict domain values to be equal to n.
Definition: bool.hpp:164
Iterator for the unknown ranges of a set variable.
Definition: set.hh:338
virtual size_t dispose(Space &)
Delete brancher and return its size.
Gecode::FloatVal c(-8, 8)
virtual void print(std::ostream &os) const
Print solution.
int p
Number of positive literals for node type.
Definition: bool-expr.cpp:236
Gecode::IntArgs i(4, 1, 2, 3, 4)
Base-class for branchers.
Definition: core.hpp:1368
BoolValBranch BOOL_VAL_MAX(void)
Select largest value.
Definition: val.hpp:139
int n
Number of negative literals for node type.
Definition: bool-expr.cpp:238
Equality ( )
Definition: int.hh:905
Options opt
The options.
Definition: test.cpp:101
Execution has resulted in failure.
Definition: core.hpp:466
Example: Peaceable co-existing armies of queens
Range iterator for computing intersection (binary)
virtual Actor * copy(Space &home)
Copy brancher during cloning.
IntSet * A
Position of a piece in a square board.
unsigned int size(I &i)
Size of all ranges of range iterator i.
void update(Space &home, VarImpVar< VarImp > &y)
Update this variable to be a clone of variable y.
Definition: var.hpp:128
const int n
Integer sets.
Definition: int.hh:174
void branching(int v)
Set default branching value.
Definition: options.hpp:229
SetVar U
Set of un-attacked squares.
virtual IntVar cost(void) const
Return solution cost.
BoolVar expr(Home home, const BoolExpr &e, IntPropLevel ipl)
Post Boolean expression and return its value.
Definition: bool-expr.cpp:632
Boolean variable array.
Definition: int.hh:787
LinIntExpr cardinality(const SetExpr &e)
Cardinality of set expression.
Definition: set-expr.cpp:818
Post propagator for SetVar SetOpType SetVar SetRelType r
Definition: set.hh:769
struct Gecode::@585::NNF::@62::@63 b
For binary nodes (and, or, eqv)
QueenArmies(QueenArmies &s)
Constructor for cloning.
Set variables
Definition: set.hh:131
virtual void archive(Archive &e) const
Archive into e.
Definition: core.cpp:857
struct Gecode::@585::NNF::@62::@64 a
For atomic nodes.
Choice for performing commit
Definition: core.hpp:1338
Archive representation
Definition: archive.hpp:46
ExecStatus
Definition: core.hpp:464
BoolVarArray b
The placement of the black queens.
Integer variables.
Definition: int.hh:351
bool assigned(View x, int v)
Whether x is assigned to value v.
Definition: single.hpp:47
void rel(Home home, FloatVar x0, FloatRelType frt, FloatVal n)
Propagates .
Definition: rel.cpp:47
virtual Space * copy(void)
Return copy during cloning.
void solutions(unsigned int n)
Set default number of solutions to search for.
Definition: options.hpp:287
Execution is okay.
Definition: core.hpp:468
Custom brancher for Peacable queens.
Gecode toplevel namespace
void assign(Home home, const FloatVarArgs &x, FloatAssign fa, FloatBranchFilter bf, FloatVarValPrint vvp)
Assign all x with value selection vals.
Definition: branch.cpp:115
Home class for posting propagators
Definition: core.hpp:846
static void post(QueenArmies &home)
Post brancher.
bool me_failed(ModEvent me)
Check whether modification event me is failed.
Definition: modevent.hpp:58
Choose variable with problem specific strategy.
Boolean view for Boolean variables.
Definition: view.hpp:1329