updated
authorChristian Urban <christian dot urban at kcl dot ac dot uk>
Mon, 31 Oct 2016 10:28:32 +0000
changeset 0 02f53f76f828
child 1 b595d654cb2d
updated
progs/knight.scala
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/progs/knight.scala	Mon Oct 31 10:28:32 2016 +0000
@@ -0,0 +1,36 @@
+
+
+def print_board(n: Int)(steps: List[(Int, Int)]): Unit = {
+  for (i <- 0 until n) {
+    for (j <- 0 until n) {
+      print(f"${steps.indexOf((i, j))}%2.0f ")
+    }
+    println
+  } 
+  //readLine()
+  System.exit(0)
+}
+
+def add_pair(x: (Int, Int))(y: (Int, Int)) = 
+  (x._1 + y._1, x._2 + y._2)
+
+def is_legal(n: Int)(x: (Int, Int)) = 
+  0 <= x._1 && 0 <= x._2 && x._1 < n && x._2 < n
+
+def moves(n: Int)(x: (Int, Int)): List[(Int, Int)] = {
+  Set((1, 2),(2, 1),(2, -1),(1, -2),
+      (-1, -2),(-2, -1),(-2, 1),(-1, 2)).map(add_pair(x)).filter(is_legal(n))
+}
+
+def tour(n: Int)(steps: List[(Int, Int)]): Unit = {
+  if (steps.length ==  n * n && moves(n)(steps.head).contains(steps.last))
+    print_board(n)(steps)
+  else 
+    for (x <- moves(n)(steps.head).par; if (!steps.contains(x))) tour(n)(x :: steps)
+}
+
+val n = 6
+
+println("started")
+for (i <- 0 until n; j <- 0 until n) tour(n)(List((i, j)))
+println("finished")