progs/knight1_sol.scala
changeset 86 f8a781322499
parent 85 fd3f8581ce85
--- a/progs/knight1_sol.scala	Thu Dec 08 12:50:54 2016 +0000
+++ b/progs/knight1_sol.scala	Tue Dec 13 13:02:52 2016 +0000
@@ -20,6 +20,10 @@
 def is_legal(dim: Int, path: Path)(x: Pos): Boolean = 
   0 <= x._1 && 0 <= x._2 && x._1 < dim && x._2 < dim && !path.contains(x)
 
+assert(is_legal(8, Nil)((3,4)) == true)
+assert(is_legal(8, List((4,1), (1,0)))((4,1)) == false)
+assert(is_legal(2, Nil)((0,0)) == true)
+
 def moves(x: Pos): List[Pos] = 
   List(( 1,  2),( 2,  1),( 2, -1),( 1, -2),
        (-1, -2),(-2, -1),(-2,  1),(-1,  2)).map(add_pair(x))
@@ -50,9 +54,9 @@
     (for (x <- legal_moves(dim, path, path.head)) yield enum_tours(dim, x::path)).flatten
 }
 
-def count_all_tours(dim: Int): Int = {
-  (for (i <- (0 until dim).toList; 
-        j <- (0 until dim).toList) yield count_tours(dim, List((i, j)))).sum
+def count_all_tours(dim: Int) = {
+  for (i <- (0 until dim).toList; 
+       j <- (0 until dim).toList) yield count_tours(dim, List((i, j)))
 }
 
 def enum_all_tours(dim: Int): List[Path] = {
@@ -60,6 +64,29 @@
         j <- (0 until dim).toList) yield enum_tours(dim, List((i, j)))).flatten
 }
 
+
+def add_pair_urban(x: Pos)(y: Pos): Pos = 
+  (x._1 + y._1, x._2 + y._2)
+
+def is_legal_urban(dim: Int, path: Path)(x: Pos): Boolean = 
+  0 <= x._1 && 0 <= x._2 && x._1 < dim && x._2 < dim && !path.contains(x)
+
+def moves_urban(x: Pos): List[Pos] = 
+  List(( 1,  2),( 2,  1),( 2, -1),( 1, -2),
+       (-1, -2),(-2, -1),(-2,  1),(-1,  2)).map(add_pair_urban(x))
+
+def legal_moves_urban(dim: Int, path: Path, x: Pos): List[Pos] = 
+  moves_urban(x).filter(is_legal_urban(dim, path))
+
+def correct_urban(dim: Int)(p: Path): Boolean = p match {
+  case Nil => true
+  case x::Nil => true
+  case x::y::p => if (legal_moves_urban(dim, p, y).contains(x)) correct_urban(dim)(y::p) else false
+}
+
+enum_tours(5, List((0, 2))).map(correct_urban(5)).forall(_ == true)
+
+
 for (dim <- 1 to 5) {
   println(s"${dim} x ${dim} " + count_tours(dim, List((0, 0))))
 }