Generated on Sat May 25 2013 18:00:32 for Gecode by doxygen 1.8.3.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-02-25 21:43:24 +0100 (Mon, 25 Feb 2013) $ by $Author: schulte $
13  * $Revision: 13406 $
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 Actor* copy(Space& home, bool share) {
144  return new (home) Warnsdorff(home, share, *this);
145  }
147  static BrancherHandle post(Home home, const IntVarArgs& x) {
148  ViewArray<Int::IntView> xv(home, x);
149  return *new (home) Warnsdorff(home, xv);
150  }
152  virtual size_t dispose(Space&) {
153  return sizeof(*this);
154  }
155 };
156 
157 
159 class Knights : public Script {
160 public:
162  const int n;
166  enum {
168  PROP_CIRCUIT
169  };
171  enum {
174  };
176  int f(int x, int y) const {
177  return x + y*n;
178  }
180  int x(int f) const {
181  return f % n;
182  }
184  int y(int f) const {
185  return f / n;
186  }
189  static const int moves[8][2] = {
190  {-2,-1}, {-2,1}, {-1,-2}, {-1,2}, {1,-2}, {1,2}, {2,-1}, {2,1}
191  };
192  int nbs[8]; int n_nbs = 0;
193  for (int m=0; m<8; m++) {
194  int nx = x(i) + moves[m][0], ny = y(i) + moves[m][1];
195  if ((nx >= 0) && (nx < n) && (ny >= 0) && (ny < n))
196  nbs[n_nbs++] = f(nx,ny);
197  }
198  return IntSet(nbs,n_nbs);
199  }
202  : n(opt.size()), succ(*this,n*n,0,n*n-1) {
203  switch (opt.branching()) {
204  case BRANCH_NAIVE:
205  branch(*this, succ, INT_VAR_NONE(), INT_VAL_MIN());
206  break;
207  case BRANCH_WARNSDORFF:
208  Warnsdorff::post(*this, succ);
209  break;
210  }
211  }
213  Knights(bool share, Knights& s) : Script(share,s), n(s.n) {
214  succ.update(*this, share, s.succ);
215  }
217  virtual void
218  print(std::ostream& os) const {
219  int* jump = new int[n*n];
220  {
221  int j=0;
222  for (int i=0; i<n*n; i++) {
223  jump[j]=i; j=succ[j].min();
224  }
225  }
226  os << "\t";
227  for (int i = 0; i < n; i++) {
228  for (int j = 0; j < n; j++) {
229  os.width(3);
230  os << jump[f(i,j)] << " ";
231  }
232  os << std::endl << "\t";
233  }
234  os << std::endl;
235  delete [] jump;
236  }
237 };
238 
249 class KnightsReified : public Knights {
250 public:
252  const int nn = n*n;
253 
254  // Map knight to its predecessor of succesor on board
255  IntVarArgs jump(nn);
256  IntVarArgs pred(nn);
257 
258  for (int i = nn; i--; ) {
259  IntVar p(*this,0,nn-1); pred[i]=p;
260  IntVar j(*this,0,nn-1); jump[i]=j;
261  }
262 
263  // Place the first two knights
264  rel(*this, jump[f(0,0)], IRT_EQ, 0);
265  rel(*this, jump[f(1,2)], IRT_EQ, 1);
266 
267  distinct(*this, jump, opt.icl());
268  channel(*this, succ, pred, opt.icl());
269 
270  for (int f = 0; f < nn; f++) {
271  IntSet ds = neighbors(f);
272  for (IntSetValues i(ds); i(); ++i)
273  rel(*this,
274  expr(*this, (jump[i.val()]-jump[f] == 1)),
275  BOT_XOR,
276  expr(*this, (jump[i.val()]-jump[f] == 1-nn)),
277  expr(*this, (succ[f] == i.val())));
278  dom(*this, pred[f], ds);
279  dom(*this, succ[f], ds);
280  rel(*this, succ[f], IRT_NQ, pred[f]);
281  }
282  }
284  KnightsReified(bool share, KnightsReified& s) : Knights(share,s) {}
286  virtual Space*
287  copy(bool share) {
288  return new KnightsReified(share,*this);
289  }
290 };
291 
302 class KnightsCircuit : public Knights {
303 public:
305  // Fix the first move
306  rel(*this, succ[0], IRT_EQ, f(1,2));
307 
308  circuit(*this, succ, opt.icl());
309 
310  for (int f = 0; f < n*n; f++)
311  dom(*this, succ[f], neighbors(f));
312  }
314  KnightsCircuit(bool share, KnightsCircuit& s) : Knights(share,s) {}
316  virtual Space*
317  copy(bool share) {
318  return new KnightsCircuit(share,*this);
319  }
320 };
321 
322 /*
323  * Just to fool some scripts:
324  * \brief %Example: n-Knight's tour
325  *
326  */
327 
328 #if defined(GECODE_HAS_QT) && defined(GECODE_HAS_GIST)
329 
330 class KnightsInspector : public Gist::Inspector {
331 protected:
333  QGraphicsScene* scene;
335  QMainWindow* mw;
337  static const int unit = 30;
338 public:
340  KnightsInspector(void) : scene(NULL), mw(NULL) {}
342  virtual void inspect(const Space& s) {
343  const Knights& k = static_cast<const Knights&>(s);
344 
345  if (!scene)
346  initialize();
347  QList <QGraphicsItem*> itemList = scene->items();
348  foreach (QGraphicsItem* i, scene->items()) {
349  scene->removeItem(i);
350  delete i;
351  }
352 
353  for (int i=0; i<k.n; i++) {
354  for (int j=0; j<k.n; j++) {
355  scene->addRect(i*unit,j*unit,unit,unit);
356 
357  QPen pen(Qt::black, 2);
358  if (!k.succ[i*k.n+j].assigned()) {
359  pen.setColor(Qt::red);
360  pen.setStyle(Qt::DotLine);
361  pen.setWidth(0);
362  }
363  for (IntVarValues xv(k.succ[i*k.n+j]); xv(); ++xv) {
364  int ky = xv.val() % k.n;
365  int kx = xv.val() / k.n;
366  scene->addLine(i*unit+unit/2,j*unit+unit/2,
367  kx*unit+unit/2,ky*unit+unit/2,
368  pen);
369  }
370 
371  }
372  }
373  mw->show();
374  }
375 
377  void initialize(void) {
378  mw = new QMainWindow();
379  scene = new QGraphicsScene();
380  QGraphicsView* view = new QGraphicsView(scene);
381  view->setRenderHints(QPainter::Antialiasing);
382  mw->setCentralWidget(view);
383  mw->setAttribute(Qt::WA_QuitOnClose, false);
384  mw->setAttribute(Qt::WA_DeleteOnClose, false);
385  QAction* closeWindow = new QAction("Close window", mw);
386  closeWindow->setShortcut(QKeySequence("Ctrl+W"));
387  mw->connect(closeWindow, SIGNAL(triggered()),
388  mw, SLOT(close()));
389  mw->addAction(closeWindow);
390  }
391 
393  virtual std::string name(void) { return "Board"; }
395  virtual void finalize(void) {
396  delete mw;
397  mw = NULL;
398  }
399 };
400 #endif
401 
405 int
406 main(int argc, char* argv[]) {
407  SizeOptions opt("Knights");
408  opt.iterations(100);
409  opt.size(8);
411  opt.propagation(Knights::PROP_REIFIED, "reified");
412  opt.propagation(Knights::PROP_CIRCUIT, "circuit");
414  opt.branching(Knights::BRANCH_NAIVE, "naive");
415  opt.branching(Knights::BRANCH_WARNSDORFF, "warnsdorff");
416 
417 #if defined(GECODE_HAS_QT) && defined(GECODE_HAS_GIST)
418  KnightsInspector ki;
419  opt.inspect.click(&ki);
420 #endif
421 
422  opt.parse(argc,argv);
423 
424  if (opt.propagation() == Knights::PROP_REIFIED) {
425  Script::run<KnightsReified,DFS,SizeOptions>(opt);
426  } else {
427  Script::run<KnightsCircuit,DFS,SizeOptions>(opt);
428  }
429  return 0;
430 }
431 
432 // STATISTICS: example-any
433