Generated on Sat Nov 9 2013 19:18:24 for Gecode by doxygen 1.8.4
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