Generated on Thu Apr 5 2018 19:44:19 for Gecode by doxygen 1.8.13
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$ by $Author$
13  * $Revision$
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 void archive(Archive& e) const {
83  e << pos << val;
84  }
85  };
86 
89  : Brancher(home), x(xv), start(0) {}
92  : Brancher(home, b), start(b.start) {
93  x.update(home, b.x);
94  }
95 public:
97  virtual bool status(const Space&) const {
98  // A path to follow can be at most x.size() long
99  for (int n=x.size(); n--; ) {
100  if (!x[start].assigned())
101  return true;
102  // Follow path of assigned variables
103  start = x[start].val();
104  }
105  return false;
106  }
109  Int::ViewValues<Int::IntView> iv(x[start]);
110  int n = iv.val();
111  unsigned int min = x[n].size();
112  ++iv;
113  // Choose the value with the fewest neighbors
114  while (iv()) {
115  if (x[iv.val()].size() < min) {
116  n = iv.val();
117  min = x[n].size();
118  }
119  ++iv;
120  }
121  return new Choice(*this, start, n);
122  }
124  virtual Choice* choice(const Space&, Archive& e) {
125  int pos, val;
126  e >> pos >> val;
127  return new Choice(*this, pos, val);
128  }
130  virtual ExecStatus commit(Space& home, const Gecode::Choice& _c,
131  unsigned int a) {
132  const Choice& c = static_cast<const Choice&>(_c);
133  if (a == 0)
134  return me_failed(x[c.pos].eq(home, c.val)) ? ES_FAILED : ES_OK;
135  else
136  return me_failed(x[c.pos].nq(home, c.val)) ? ES_FAILED : ES_OK;
137  }
139  virtual void print(const Space&, const Gecode::Choice& _c,
140  unsigned int a,
141  std::ostream& o) const {
142  const Choice& c = static_cast<const Choice&>(_c);
143  o << "x[" << c.pos << "] "
144  << ((a == 0) ? "=" : "!=")
145  << " " << c.val;
146  }
148  virtual Actor* copy(Space& home) {
149  return new (home) Warnsdorff(home, *this);
150  }
152  static void post(Home home, const IntVarArgs& x) {
153  ViewArray<Int::IntView> xv(home, x);
154  (void) new (home) Warnsdorff(home, xv);
155  }
157  virtual size_t dispose(Space&) {
158  return sizeof(*this);
159  }
160 };
161 
162 
164 class Knights : public Script {
165 public:
167  const int n;
171  enum {
173  PROP_CIRCUIT
174  };
176  enum {
179  };
181  int f(int x, int y) const {
182  return x + y*n;
183  }
185  int x(int f) const {
186  return f % n;
187  }
189  int y(int f) const {
190  return f / n;
191  }
194  static const int moves[8][2] = {
195  {-2,-1}, {-2,1}, {-1,-2}, {-1,2}, {1,-2}, {1,2}, {2,-1}, {2,1}
196  };
197  int nbs[8]; int n_nbs = 0;
198  for (int m=0; m<8; m++) {
199  int nx = x(i) + moves[m][0], ny = y(i) + moves[m][1];
200  if ((nx >= 0) && (nx < n) && (ny >= 0) && (ny < n))
201  nbs[n_nbs++] = f(nx,ny);
202  }
203  return IntSet(nbs,n_nbs);
204  }
207  : Script(opt), n(opt.size()), succ(*this,n*n,0,n*n-1) {
208  switch (opt.branching()) {
209  case BRANCH_NAIVE:
210  branch(*this, succ, INT_VAR_NONE(), INT_VAL_MIN());
211  break;
212  case BRANCH_WARNSDORFF:
213  Warnsdorff::post(*this, succ);
214  break;
215  }
216  }
218  Knights(Knights& s) : Script(s), n(s.n) {
219  succ.update(*this, s.succ);
220  }
222  virtual void
223  print(std::ostream& os) const {
224  int* jump = new int[n*n];
225  {
226  int j=0;
227  for (int i=0; i<n*n; i++) {
228  jump[j]=i; j=succ[j].min();
229  }
230  }
231  os << "\t";
232  for (int i = 0; i < n; i++) {
233  for (int j = 0; j < n; j++) {
234  os.width(3);
235  os << jump[f(i,j)] << " ";
236  }
237  os << std::endl << "\t";
238  }
239  os << std::endl;
240  delete [] jump;
241  }
242 };
243 
254 class KnightsReified : public Knights {
255 public:
257  const int nn = n*n;
258 
259  // Map knight to its predecessor of succesor on board
260  IntVarArgs jump(nn);
261  IntVarArgs pred(nn);
262 
263  for (int i = nn; i--; ) {
264  IntVar p(*this,0,nn-1); pred[i]=p;
265  IntVar j(*this,0,nn-1); jump[i]=j;
266  }
267 
268  // Place the first two knights
269  rel(*this, jump[f(0,0)], IRT_EQ, 0);
270  rel(*this, jump[f(1,2)], IRT_EQ, 1);
271 
272  distinct(*this, jump, opt.ipl());
273  channel(*this, succ, pred, opt.ipl());
274 
275  for (int f = 0; f < nn; f++) {
276  IntSet ds = neighbors(f);
277  for (IntSetValues i(ds); i(); ++i)
278  rel(*this,
279  expr(*this, (jump[i.val()]-jump[f] == 1)),
280  BOT_XOR,
281  expr(*this, (jump[i.val()]-jump[f] == 1-nn)),
282  expr(*this, (succ[f] == i.val())));
283  dom(*this, pred[f], ds);
284  dom(*this, succ[f], ds);
285  rel(*this, succ[f], IRT_NQ, pred[f]);
286  }
287  }
291  virtual Space*
292  copy(void) {
293  return new KnightsReified(*this);
294  }
295 };
296 
307 class KnightsCircuit : public Knights {
308 public:
310  // Fix the first move
311  rel(*this, succ[0], IRT_EQ, f(1,2));
312 
313  circuit(*this, succ, opt.ipl());
314 
315  for (int f = 0; f < n*n; f++)
316  dom(*this, succ[f], neighbors(f));
317  }
321  virtual Space*
322  copy(void) {
323  return new KnightsCircuit(*this);
324  }
325 };
326 
327 /*
328  * Just to fool some scripts:
329  * \brief %Example: n-Knight's tour
330  *
331  */
332 
333 #if defined(GECODE_HAS_QT) && defined(GECODE_HAS_GIST)
334 class KnightsInspector : public Gist::Inspector {
336 protected:
338  QGraphicsScene* scene;
340  QMainWindow* mw;
342  static const int unit = 30;
343 public:
345  KnightsInspector(void) : scene(NULL), mw(NULL) {}
347  virtual void inspect(const Space& s) {
348  const Knights& k = static_cast<const Knights&>(s);
349 
350  if (!scene)
351  initialize();
352  QList <QGraphicsItem*> itemList = scene->items();
353  foreach (QGraphicsItem* i, scene->items()) {
354  scene->removeItem(i);
355  delete i;
356  }
357 
358  for (int i=0; i<k.n; i++) {
359  for (int j=0; j<k.n; j++) {
360  scene->addRect(i*unit,j*unit,unit,unit);
361 
362  QPen pen(Qt::black, 2);
363  if (!k.succ[i*k.n+j].assigned()) {
364  pen.setColor(Qt::red);
365  pen.setStyle(Qt::DotLine);
366  pen.setWidth(0);
367  }
368  for (IntVarValues xv(k.succ[i*k.n+j]); xv(); ++xv) {
369  int ky = xv.val() % k.n;
370  int kx = xv.val() / k.n;
371  scene->addLine(i*unit+unit/2,j*unit+unit/2,
372  kx*unit+unit/2,ky*unit+unit/2,
373  pen);
374  }
375 
376  }
377  }
378  mw->show();
379  }
380 
382  void initialize(void) {
383  mw = new QMainWindow();
384  scene = new QGraphicsScene();
385  QGraphicsView* view = new QGraphicsView(scene);
386  view->setRenderHints(QPainter::Antialiasing);
387  mw->setCentralWidget(view);
388  mw->setAttribute(Qt::WA_QuitOnClose, false);
389  mw->setAttribute(Qt::WA_DeleteOnClose, false);
390  QAction* closeWindow = new QAction("Close window", mw);
391  closeWindow->setShortcut(QKeySequence("Ctrl+W"));
392  mw->connect(closeWindow, SIGNAL(triggered()),
393  mw, SLOT(close()));
394  mw->addAction(closeWindow);
395  }
396 
398  virtual std::string name(void) { return "Board"; }
400  virtual void finalize(void) {
401  delete mw;
402  mw = NULL;
403  }
404 };
405 #endif
406 
410 int
411 main(int argc, char* argv[]) {
412  SizeOptions opt("Knights");
413  opt.iterations(100);
414  opt.size(8);
416  opt.propagation(Knights::PROP_REIFIED, "reified");
417  opt.propagation(Knights::PROP_CIRCUIT, "circuit");
419  opt.branching(Knights::BRANCH_NAIVE, "naive");
420  opt.branching(Knights::BRANCH_WARNSDORFF, "warnsdorff");
421 
422 #if defined(GECODE_HAS_QT) && defined(GECODE_HAS_GIST)
423  KnightsInspector ki;
424  opt.inspect.click(&ki);
425 #endif
426 
427  opt.parse(argc,argv);
428 
429  if (opt.propagation() == Knights::PROP_REIFIED) {
430  Script::run<KnightsReified,DFS,SizeOptions>(opt);
431  } else {
432  Script::run<KnightsCircuit,DFS,SizeOptions>(opt);
433  }
434  return 0;
435 }
436 
437 // STATISTICS: example-any
438 
Value iterator for integer variables.
Definition: int.hh:470
int y(int f) const
Return y coordinate at field f.
Definition: knights.cpp:189
void size(unsigned int s)
Set default size.
Definition: options.hpp:590
Knights(Knights &s)
Constructor for cloning s.
Definition: knights.cpp:218
Options for scripts with additional size parameter
Definition: driver.hh:679
Warnsdorff(Home home, ViewArray< Int::IntView > &xv)
Construct brancher.
Definition: knights.cpp:88
Use single circuit constraints.
Definition: knights.cpp:173
virtual Space * copy(void)
Copy during cloning.
Definition: knights.cpp:322
IntVarBranch INT_VAR_NONE(void)
Select first unassigned variable.
Definition: var.hpp:100
void update(Space &home, ViewArray< View > &a)
Update array to be a clone of array a.
Definition: array.hpp:1375
const int n
Size of board.
Definition: knights.cpp:167
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
virtual size_t dispose(Space &)
Delete brancher and return its size.
Definition: knights.cpp:157
void channel(Home home, FloatVar x0, IntVar x1)
Post propagator for channeling a float and an integer variable .
Definition: channel.cpp:45
void propagation(int v)
Set default propagation value.
Definition: options.hpp:207
void update(Space &home, VarArray< Var > &a)
Update array to be a clone of array a.
Definition: array.hpp:1060
void parse(int &argc, char *argv[])
Parse options from arguments argv (number is argc)
Definition: options.cpp:670
Example: n-Knights tour (model using circuit)
Definition: knights.cpp:307
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 Space * copy(void)
Copy during cloning.
Definition: knights.cpp:292
void dom(Home home, FloatVar x, FloatVal n)
Propagates .
Definition: dom.cpp:44
Integer variable array.
Definition: int.hh:742
Multi _c(Gecode::IntArgs(3, 1, 2, 3))
class Gecode::Options::_I inspect
void circuit(Home home, int offset, const IntVarArgs &x, IntPropLevel ipl)
Post propagator such that x forms a circuit.
Definition: circuit.cpp:45
void ipl(IntPropLevel i)
Set default integer propagation level.
Definition: options.hpp:220
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
Computation spaces.
Definition: core.hpp:1668
Abstract base class for inspectors.
Definition: gist.hh:103
Parametric base-class for scripts.
Definition: driver.hh:733
void iterations(unsigned int i)
Set default number of iterations.
Definition: options.hpp:465
int val(void) const
Return current value.
Exclusive or.
Definition: int.hh:934
Base-class for both propagators and branchers.
Definition: core.hpp:620
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
int f(int x, int y) const
Return field at position x, y.
Definition: knights.cpp:181
Gecode::IntArgs i(4, 1, 2, 3, 4)
virtual Gecode::Choice * choice(Space &)
Return choice.
Definition: knights.cpp:108
Base-class for branchers.
Definition: core.hpp:1368
Example: n-Knight&#39;s tour (simple model)
Definition: knights.cpp:254
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
KnightsCircuit(const SizeOptions &opt)
Definition: knights.cpp:309
IntValBranch INT_VAL_MIN(void)
Select smallest value.
Definition: val.hpp:59
unsigned int size(I &i)
Size of all ranges of range iterator i.
void click(Gist::Inspector *i)
Add inspector that reacts on node double clicks.
Definition: options.hpp:552
void distinct(Home home, const IntVarArgs &x, IntPropLevel ipl)
Post propagator for for all .
Definition: distinct.cpp:50
static void post(Home home, const IntVarArgs &x)
Post brancher.
Definition: knights.cpp:152
Knights(const SizeOptions &opt)
Constructor.
Definition: knights.cpp:206
Integer sets.
Definition: int.hh:174
void branching(int v)
Set default branching value.
Definition: options.hpp:229
virtual bool status(const Space &) const
Check status of brancher, return true if alternatives left.
Definition: knights.cpp:97
Passing integer variables.
Definition: int.hh:637
BoolVar expr(Home home, const BoolExpr &e, IntPropLevel ipl)
Post Boolean expression and return its value.
Definition: bool-expr.cpp:632
void min(Home home, FloatVar x0, FloatVar x1, FloatVar x2)
Post propagator for .
Definition: arithmetic.cpp:71
struct Gecode::@585::NNF::@62::@63 b
For binary nodes (and, or, eqv)
KnightsReified(const SizeOptions &opt)
Definition: knights.cpp:256
Post propagator for f(x \diamond_{\mathit{op}} y) \sim_r z \f$ void rel(Home home
Post propagator for SetVar SetOpType SetVar y
Definition: set.hh:769
int main(int argc, char *argv[])
Main-function.
Definition: knights.cpp:411
int x(int f) const
Return x coordinate at field f.
Definition: knights.cpp:185
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
int start
Next variable to branch on.
Definition: knights.cpp:67
Base-class for knight&#39;s tour example.
Definition: knights.cpp:164
Archive representation
Definition: archive.hpp:46
Use Warnsdorff&#39;s rule.
Definition: knights.cpp:178
ExecStatus
Definition: core.hpp:464
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
Use reified constraints.
Definition: knights.cpp:172
virtual void print(const Space &, const Gecode::Choice &_c, unsigned int a, std::ostream &o) const
Print explanation.
Definition: knights.cpp:139
Custom brancher for knight&#39;s tours using Warnsdorff&#39;s rule.
Definition: knights.cpp:62
Value iterator for integer sets.
Definition: int.hh:313
virtual void print(std::ostream &os) const
Print board.
Definition: knights.cpp:223
Post propagator for SetVar x
Definition: set.hh:769
virtual Actor * copy(Space &home)
Copy brancher.
Definition: knights.cpp:148
Execution is okay.
Definition: core.hpp:468
Use naive, lexicographical branching.
Definition: knights.cpp:177
IntSet neighbors(int i)
Compute set of neighbour fields.
Definition: knights.cpp:193
Choice(const Brancher &b, int pos0, int val0)
Definition: knights.cpp:78
virtual void archive(Archive &e) const
Archive into e.
Definition: knights.cpp:81
virtual Choice * choice(const Space &, Archive &e)
Return choice.
Definition: knights.cpp:124
Gecode toplevel namespace
Disequality ( )
Definition: int.hh:906
int size(void) const
Return size of array (number of elements)
Definition: array.hpp:1203
IntVarArray succ
Maps board field to successor field.
Definition: knights.cpp:169
Home class for posting propagators
Definition: core.hpp:846
KnightsReified(KnightsReified &s)
Constructor for cloning s.
Definition: knights.cpp:289
virtual ExecStatus commit(Space &home, const Gecode::Choice &_c, unsigned int a)
Perform commit for choice _c and alternative a.
Definition: knights.cpp:130
bool me_failed(ModEvent me)
Check whether modification event me is failed.
Definition: modevent.hpp:58
Warnsdorff(Space &home, Warnsdorff &b)
Copy constructor.
Definition: knights.cpp:91
KnightsCircuit(KnightsCircuit &s)
Constructor for cloning s.
Definition: knights.cpp:319