Generated on Sat Feb 7 2015 02:01:11 for Gecode by doxygen 1.8.9.1
knights.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  * Christian Schulte <schulte@gecode.org>
6  *
7  * Copyright:
8  * Mikael Lagerkvist, 2008
9  * Christian Schulte, 2001
10  *
11  * Last modified:
12  * $Date: 2013-07-08 14:22:40 +0200 (Mon, 08 Jul 2013) $ by $Author: schulte $
13  * $Revision: 13820 $
14  *
15  * This file is part of Gecode, the generic constraint
16  * development environment:
17  * http://www.gecode.org
18  *
19  * Permission is hereby granted, free of charge, to any person obtaining
20  * a copy of this software and associated documentation files (the
21  * "Software"), to deal in the Software without restriction, including
22  * without limitation the rights to use, copy, modify, merge, publish,
23  * distribute, sublicense, and/or sell copies of the Software, and to
24  * permit persons to whom the Software is furnished to do so, subject to
25  * the following conditions:
26  *
27  * The above copyright notice and this permission notice shall be
28  * included in all copies or substantial portions of the Software.
29  *
30  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
31  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
33  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
34  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
35  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
36  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37  *
38  */
39 
40 #include <gecode/driver.hh>
41 #include <gecode/int.hh>
42 #include <gecode/minimodel.hh>
43 
44 #if defined(GECODE_HAS_QT) && defined(GECODE_HAS_GIST)
45 #include <QtGui>
46 #if QT_VERSION >= 0x050000
47 #include <QtWidgets>
48 #endif
49 #endif
50 
51 using namespace Gecode;
52 
53 
62 class Warnsdorff : public Brancher {
63 protected:
67  mutable int start;
69  class Choice : public Gecode::Choice {
70  public:
72  int pos;
74  int val;
78  Choice(const Brancher& b, int pos0, int val0)
79  : Gecode::Choice(b,2), pos(pos0), val(val0) {}
81  virtual size_t size(void) const {
82  return sizeof(Choice);
83  }
85  virtual void archive(Archive& e) const {
87  e << pos << val;
88  }
89  };
90 
93  : Brancher(home), x(xv), start(0) {}
95  Warnsdorff(Space& home, bool share, Warnsdorff& b)
96  : Brancher(home, share, b), start(b.start) {
97  x.update(home, share, b.x);
98  }
99 public:
101  virtual bool status(const Space&) const {
102  // A path to follow can be at most x.size() long
103  for (int n=x.size(); n--; ) {
104  if (!x[start].assigned())
105  return true;
106  // Follow path of assigned variables
107  start = x[start].val();
108  }
109  return false;
110  }
113  Int::ViewValues<Int::IntView> iv(x[start]);
114  int n = iv.val();
115  unsigned int min = x[n].size();
116  ++iv;
117  // Choose the value with the fewest neighbors
118  while (iv()) {
119  if (x[iv.val()].size() < min) {
120  n = iv.val();
121  min = x[n].size();
122  }
123  ++iv;
124  }
125  return new Choice(*this, start, n);
126  }
128  virtual Choice* choice(const Space&, Archive& e) {
129  int pos, val;
130  e >> pos >> val;
131  return new Choice(*this, pos, val);
132  }
134  virtual ExecStatus commit(Space& home, const Gecode::Choice& _c,
135  unsigned int a) {
136  const Choice& c = static_cast<const Choice&>(_c);
137  if (a == 0)
138  return me_failed(x[c.pos].eq(home, c.val)) ? ES_FAILED : ES_OK;
139  else
140  return me_failed(x[c.pos].nq(home, c.val)) ? ES_FAILED : ES_OK;
141  }
143  virtual void print(const Space&, const Gecode::Choice& _c,
144  unsigned int a,
145  std::ostream& o) const {
146  const Choice& c = static_cast<const Choice&>(_c);
147  o << "x[" << c.pos << "] "
148  << ((a == 0) ? "=" : "!=")
149  << " " << c.val;
150  }
152  virtual Actor* copy(Space& home, bool share) {
153  return new (home) Warnsdorff(home, share, *this);
154  }
156  static BrancherHandle post(Home home, const IntVarArgs& x) {
157  ViewArray<Int::IntView> xv(home, x);
158  return *new (home) Warnsdorff(home, xv);
159  }
161  virtual size_t dispose(Space&) {
162  return sizeof(*this);
163  }
164 };
165 
166 
168 class Knights : public Script {
169 public:
171  const int n;
175  enum {
177  PROP_CIRCUIT
178  };
180  enum {
183  };
185  int f(int x, int y) const {
186  return x + y*n;
187  }
189  int x(int f) const {
190  return f % n;
191  }
193  int y(int f) const {
194  return f / n;
195  }
198  static const int moves[8][2] = {
199  {-2,-1}, {-2,1}, {-1,-2}, {-1,2}, {1,-2}, {1,2}, {2,-1}, {2,1}
200  };
201  int nbs[8]; int n_nbs = 0;
202  for (int m=0; m<8; m++) {
203  int nx = x(i) + moves[m][0], ny = y(i) + moves[m][1];
204  if ((nx >= 0) && (nx < n) && (ny >= 0) && (ny < n))
205  nbs[n_nbs++] = f(nx,ny);
206  }
207  return IntSet(nbs,n_nbs);
208  }
211  : n(opt.size()), succ(*this,n*n,0,n*n-1) {
212  switch (opt.branching()) {
213  case BRANCH_NAIVE:
214  branch(*this, succ, INT_VAR_NONE(), INT_VAL_MIN());
215  break;
216  case BRANCH_WARNSDORFF:
217  Warnsdorff::post(*this, succ);
218  break;
219  }
220  }
222  Knights(bool share, Knights& s) : Script(share,s), n(s.n) {
223  succ.update(*this, share, s.succ);
224  }
226  virtual void
227  print(std::ostream& os) const {
228  int* jump = new int[n*n];
229  {
230  int j=0;
231  for (int i=0; i<n*n; i++) {
232  jump[j]=i; j=succ[j].min();
233  }
234  }
235  os << "\t";
236  for (int i = 0; i < n; i++) {
237  for (int j = 0; j < n; j++) {
238  os.width(3);
239  os << jump[f(i,j)] << " ";
240  }
241  os << std::endl << "\t";
242  }
243  os << std::endl;
244  delete [] jump;
245  }
246 };
247 
258 class KnightsReified : public Knights {
259 public:
261  const int nn = n*n;
262 
263  // Map knight to its predecessor of succesor on board
264  IntVarArgs jump(nn);
265  IntVarArgs pred(nn);
266 
267  for (int i = nn; i--; ) {
268  IntVar p(*this,0,nn-1); pred[i]=p;
269  IntVar j(*this,0,nn-1); jump[i]=j;
270  }
271 
272  // Place the first two knights
273  rel(*this, jump[f(0,0)], IRT_EQ, 0);
274  rel(*this, jump[f(1,2)], IRT_EQ, 1);
275 
276  distinct(*this, jump, opt.icl());
277  channel(*this, succ, pred, opt.icl());
278 
279  for (int f = 0; f < nn; f++) {
280  IntSet ds = neighbors(f);
281  for (IntSetValues i(ds); i(); ++i)
282  rel(*this,
283  expr(*this, (jump[i.val()]-jump[f] == 1)),
284  BOT_XOR,
285  expr(*this, (jump[i.val()]-jump[f] == 1-nn)),
286  expr(*this, (succ[f] == i.val())));
287  dom(*this, pred[f], ds);
288  dom(*this, succ[f], ds);
289  rel(*this, succ[f], IRT_NQ, pred[f]);
290  }
291  }
293  KnightsReified(bool share, KnightsReified& s) : Knights(share,s) {}
295  virtual Space*
296  copy(bool share) {
297  return new KnightsReified(share,*this);
298  }
299 };
300 
311 class KnightsCircuit : public Knights {
312 public:
314  // Fix the first move
315  rel(*this, succ[0], IRT_EQ, f(1,2));
316 
317  circuit(*this, succ, opt.icl());
318 
319  for (int f = 0; f < n*n; f++)
320  dom(*this, succ[f], neighbors(f));
321  }
323  KnightsCircuit(bool share, KnightsCircuit& s) : Knights(share,s) {}
325  virtual Space*
326  copy(bool share) {
327  return new KnightsCircuit(share,*this);
328  }
329 };
330 
331 /*
332  * Just to fool some scripts:
333  * \brief %Example: n-Knight's tour
334  *
335  */
336 
337 #if defined(GECODE_HAS_QT) && defined(GECODE_HAS_GIST)
338 class KnightsInspector : public Gist::Inspector {
340 protected:
342  QGraphicsScene* scene;
344  QMainWindow* mw;
346  static const int unit = 30;
347 public:
349  KnightsInspector(void) : scene(NULL), mw(NULL) {}
351  virtual void inspect(const Space& s) {
352  const Knights& k = static_cast<const Knights&>(s);
353 
354  if (!scene)
355  initialize();
356  QList <QGraphicsItem*> itemList = scene->items();
357  foreach (QGraphicsItem* i, scene->items()) {
358  scene->removeItem(i);
359  delete i;
360  }
361 
362  for (int i=0; i<k.n; i++) {
363  for (int j=0; j<k.n; j++) {
364  scene->addRect(i*unit,j*unit,unit,unit);
365 
366  QPen pen(Qt::black, 2);
367  if (!k.succ[i*k.n+j].assigned()) {
368  pen.setColor(Qt::red);
369  pen.setStyle(Qt::DotLine);
370  pen.setWidth(0);
371  }
372  for (IntVarValues xv(k.succ[i*k.n+j]); xv(); ++xv) {
373  int ky = xv.val() % k.n;
374  int kx = xv.val() / k.n;
375  scene->addLine(i*unit+unit/2,j*unit+unit/2,
376  kx*unit+unit/2,ky*unit+unit/2,
377  pen);
378  }
379 
380  }
381  }
382  mw->show();
383  }
384 
386  void initialize(void) {
387  mw = new QMainWindow();
388  scene = new QGraphicsScene();
389  QGraphicsView* view = new QGraphicsView(scene);
390  view->setRenderHints(QPainter::Antialiasing);
391  mw->setCentralWidget(view);
392  mw->setAttribute(Qt::WA_QuitOnClose, false);
393  mw->setAttribute(Qt::WA_DeleteOnClose, false);
394  QAction* closeWindow = new QAction("Close window", mw);
395  closeWindow->setShortcut(QKeySequence("Ctrl+W"));
396  mw->connect(closeWindow, SIGNAL(triggered()),
397  mw, SLOT(close()));
398  mw->addAction(closeWindow);
399  }
400 
402  virtual std::string name(void) { return "Board"; }
404  virtual void finalize(void) {
405  delete mw;
406  mw = NULL;
407  }
408 };
409 #endif
410 
414 int
415 main(int argc, char* argv[]) {
416  SizeOptions opt("Knights");
417  opt.iterations(100);
418  opt.size(8);
420  opt.propagation(Knights::PROP_REIFIED, "reified");
421  opt.propagation(Knights::PROP_CIRCUIT, "circuit");
423  opt.branching(Knights::BRANCH_NAIVE, "naive");
424  opt.branching(Knights::BRANCH_WARNSDORFF, "warnsdorff");
425 
426 #if defined(GECODE_HAS_QT) && defined(GECODE_HAS_GIST)
427  KnightsInspector ki;
428  opt.inspect.click(&ki);
429 #endif
430 
431  opt.parse(argc,argv);
432 
433  if (opt.propagation() == Knights::PROP_REIFIED) {
434  Script::run<KnightsReified,DFS,SizeOptions>(opt);
435  } else {
436  Script::run<KnightsCircuit,DFS,SizeOptions>(opt);
437  }
438  return 0;
439 }
440 
441 // STATISTICS: example-any
442 
Value iterator for integer variables.
Definition: int.hh:469
void size(unsigned int s)
Set default size.
Definition: options.hpp:467
Options for scripts with additional size parameter
Definition: driver.hh:567
Warnsdorff(Home home, ViewArray< Int::IntView > &xv)
Construct brancher.
Definition: knights.cpp:92
void update(Space &, bool share, ViewArray< View > &a)
Update array to be a clone of array a.
Definition: array.hpp:1387
IntVarBranch INT_VAR_NONE(void)
Select first unassigned variable.
Definition: var.hpp:108
virtual void print(const Space &, const Gecode::Choice &_c, unsigned int a, std::ostream &o) const
Print explanation.
Definition: knights.cpp:143
const int n
Size of board.
Definition: knights.cpp:171
virtual size_t dispose(Space &)
Delete brancher and return its size.
Definition: knights.cpp:161
void channel(Home home, FloatVar x0, IntVar x1)
Post propagator for channeling a float and an integer variable .
Definition: arithmetic.cpp:218
void propagation(int v)
Set default propagation value.
Definition: options.hpp:181
virtual void archive(Archive &e) const
Archive into e.
Definition: knights.cpp:85
KnightsReified(bool share, KnightsReified &s)
Constructor for cloning s.
Definition: knights.cpp:293
void parse(int &argc, char *argv[])
Parse options from arguments argv (number is argc)
Definition: options.cpp:435
Handle for brancher.
Definition: core.hpp:1157
Example: n-Knights tour (model using circuit)
Definition: knights.cpp:311
bool pos(const View &x)
Test whether x is postive.
Definition: mult.hpp:45
Use Warnsdorff's rule.
Definition: knights.cpp:182
void dom(Home home, FloatVar x, FloatVal n)
Propagates .
Definition: dom.cpp:44
int f(int x, int y) const
Return field at position x, y.
Definition: knights.cpp:185
Integer variable array.
Definition: int.hh:741
virtual size_t size(void) const
Report size occupied.
Definition: knights.cpp:81
int x(int f) const
Return x coordinate at field f.
Definition: knights.cpp:189
Value iterator for integer views.
Definition: view.hpp:94
int pos
Position of variable.
Definition: knights.cpp:72
ViewArray< Int::IntView > x
Views of the brancher.
Definition: knights.cpp:65
int y(int f) const
Return y coordinate at field f.
Definition: knights.cpp:193
Computation spaces.
Definition: core.hpp:1362
Abstract base class for inspectors.
Definition: gist.hh:103
Parametric base-class for scripts.
Definition: driver.hh:622
void iterations(unsigned int i)
Set default number of iterations.
Definition: options.hpp:385
virtual Space * copy(bool share)
Copy during cloning.
Definition: knights.cpp:326
Exclusive or.
Definition: int.hh:921
Base-class for both propagators and branchers.
Definition: core.hpp:666
KnightsCircuit(bool share, KnightsCircuit &s)
Constructor for cloning s.
Definition: knights.cpp:323
Knights(bool share, Knights &s)
Constructor for cloning s.
Definition: knights.cpp:222
void update(Space &, bool share, VarArray< Var > &a)
Update array to be a clone of array a.
Definition: array.hpp:1072
virtual bool status(const Space &) const
Check status of brancher, return true if alternatives left.
Definition: knights.cpp:101
Gecode::FloatVal c(-8, 8)
int val
Value of variable.
Definition: knights.cpp:74
int p
Number of positive literals for node type.
Definition: bool-expr.cpp:236
Gecode::IntArgs i(4, 1, 2, 3, 4)
virtual Gecode::Choice * choice(Space &)
Return choice.
Definition: knights.cpp:112
Base-class for branchers.
Definition: core.hpp:1071
Example: n-Knight's tour (simple model)
Definition: knights.cpp:258
int n
Number of negative literals for node type.
Definition: bool-expr.cpp:238
Equality ( )
Definition: int.hh:904
Options opt
The options.
Definition: test.cpp:101
Execution has resulted in failure.
Definition: core.hpp:525
KnightsCircuit(const SizeOptions &opt)
Definition: knights.cpp:313
IntValBranch INT_VAL_MIN(void)
Select smallest value.
Definition: val.hpp:68
virtual void archive(Archive &e) const
Archive into e.
Definition: core.cpp:670
unsigned int size(I &i)
Size of all ranges of range iterator i.
Use single circuit constraints.
Definition: knights.cpp:177
Knights(const SizeOptions &opt)
Constructor.
Definition: knights.cpp:210
Integer sets.
Definition: int.hh:171
void branching(int v)
Set default branching value.
Definition: options.hpp:203
virtual Actor * copy(Space &home, bool share)
Copy brancher.
Definition: knights.cpp:152
Passing integer variables.
Definition: int.hh:636
void min(Home home, FloatVar x0, FloatVar x1, FloatVar x2)
Post propagator for .
Definition: arithmetic.cpp:75
KnightsReified(const SizeOptions &opt)
Definition: knights.cpp:260
BoolVar expr(Home home, const BoolExpr &e, IntConLevel icl)
Post Boolean expression and return its value.
Definition: bool-expr.cpp:632
Use reified constraints.
Definition: knights.cpp:176
int main(int argc, char *argv[])
Main-function.
Definition: knights.cpp:415
Node * x
Pointer to corresponding Boolean expression node.
Definition: bool-expr.cpp:253
Choice for performing commit
Definition: core.hpp:1036
int start
Next variable to branch on.
Definition: knights.cpp:67
Base-class for knight's tour example.
Definition: knights.cpp:168
Archive representation
Definition: archive.hpp:45
ExecStatus
Definition: core.hpp:523
Integer variables.
Definition: int.hh:350
bool assigned(View x, int v)
Whether x is assigned to value v.
Definition: single.hpp:47
virtual Space * copy(bool share)
Copy during cloning.
Definition: knights.cpp:296
void rel(Home home, FloatVar x0, FloatRelType frt, FloatVal n)
Propagates .
Definition: rel.cpp:47
Custom brancher for knight's tours using Warnsdorff's rule.
Definition: knights.cpp:62
Value iterator for integer sets.
Definition: int.hh:312
void distinct(Home home, const IntVarArgs &x, IntConLevel icl)
Post propagator for for all .
Definition: distinct.cpp:47
virtual void print(std::ostream &os) const
Print board.
Definition: knights.cpp:227
Execution is okay.
Definition: core.hpp:527
static BrancherHandle post(Home home, const IntVarArgs &x)
Post brancher.
Definition: knights.cpp:156
Warnsdorff(Space &home, bool share, Warnsdorff &b)
Copy constructor.
Definition: knights.cpp:95
int val(void) const
Return current value.
int size(void) const
Return size of array (number of elements)
Definition: array.hpp:1215
IntSet neighbors(int i)
Compute set of neighbour fields.
Definition: knights.cpp:197
Use naive, lexicographical branching.
Definition: knights.cpp:181
Choice(const Brancher &b, int pos0, int val0)
Definition: knights.cpp:78
struct Gecode::@518::NNF::@57::@58 b
For binary nodes (and, or, eqv)
virtual Choice * choice(const Space &, Archive &e)
Return choice.
Definition: knights.cpp:128
Gecode toplevel namespace
Disequality ( )
Definition: int.hh:905
bool assigned(void) const
Test if all variables are assigned.
Definition: array.hpp:1085
BrancherHandle 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
void circuit(Home home, int offset, const IntVarArgs &x, IntConLevel icl)
Post propagator such that x forms a circuit.
Definition: circuit.cpp:45
IntVarArray succ
Maps board field to successor field.
Definition: knights.cpp:173
Home class for posting propagators
Definition: core.hpp:717
void icl(IntConLevel i)
Set default integer consistency level.
Definition: options.hpp:194
struct Gecode::@518::NNF::@57::@59 a
For atomic nodes.
virtual ExecStatus commit(Space &home, const Gecode::Choice &_c, unsigned int a)
Perform commit for choice _c and alternative a.
Definition: knights.cpp:134
bool me_failed(ModEvent me)
Check whether modification event me is failed.
Definition: modevent.hpp:58
Multi _c(Gecode::IntArgs(3, 1, 2, 3))