progs/knight3.scala
changeset 213 f968188d4a9b
parent 53 9f8751912560
--- a/progs/knight3.scala	Tue Nov 20 14:31:14 2018 +0000
+++ b/progs/knight3.scala	Thu Nov 22 17:19:23 2018 +0000
@@ -1,24 +1,124 @@
 // Part 3 about finding a single tour using the Warnsdorf Rule
 //=============================================================
 
-// copy any function you need from files knight1.scala and
-// knight2.scala
+
+type Pos = (Int, Int)
+type Path = List[Pos]
+
+// for measuring time
+def time_needed[T](n: Int, code: => T) : T = {
+  val start = System.nanoTime()
+  for (i <- 0 until n) code
+  val result = code
+  val end = System.nanoTime()
+  println(f"Time needed: ${(end - start) / 1.0e9}%3.3f secs.")
+  result
+}
+
+def print_board(dim: Int, path: Path): Unit = {
+  println
+  for (i <- 0 until dim) {
+    for (j <- 0 until dim) {
+      print(f"${path.reverse.indexOf((i, j))}%4.0f ")
+    }
+    println
+  } 
+}
+
+def add_pair(x: Pos, y: Pos): Pos = 
+  (x._1 + y._1, x._2 + y._2)
 
-type Pos = (Int, Int)    // a position on a chessboard 
-type Path = List[Pos]    // a path...a list of positions
+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)
+
+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, _))
+
+def legal_moves(dim: Int, path: Path, x: Pos): List[Pos] = 
+  moves(x).filter(is_legal(dim, path, _))
+
+def ordered_moves(dim: Int, path: Path, x: Pos): List[Pos] = 
+  legal_moves(dim, path, x).sortBy((x) => legal_moves(dim, path, x).length)
 
-//(3a) Complete the function that calculates a list of onward
-// moves like in (1b) but orders them according to the Warnsdorf’s 
-// rule. That means moves with the fewest legal onward moves 
-// should come first.
+import scala.annotation.tailrec
+
+@tailrec
+def first(xs: List[Pos], f: Pos => Option[Path]): Option[Path] = xs match {
+  case Nil => None
+  case x::xs => {
+    val result = f(x)
+    if (result.isDefined) result else first(xs, f)
+  }
+}
+
+
+//def first[A, B](xs: List[A], f: A => Option[B]): Option[B] =
+//  xs.flatMap(f(_)).headOption
+
 
-def ordered_moves(dim: Int, path: Path, x: Pos): List[Pos] = ..
+def first_closed_tour_heuristics(dim: Int, path: Path): Option[Path] = {
+  if (path.length == dim * dim && moves(path.head).contains(path.last)) Some(path)
+  else
+    first(ordered_moves(dim, path, path.head), (x: Pos) => first_closed_tour_heuristics(dim, x::path))
+}
+
+// heuristic cannot be used to search for closed tours on 7 x 7
+for (dim <- 1 to 6) {
+  val t = time_needed(0, first_closed_tour_heuristics(dim, List((dim / 2, dim / 2))))
+  println(s"${dim} x ${dim} closed: " + (if (t == None) "" else { print_board(dim, t.get) ; "" }))
+}
+
 
-//(3b) Complete the function that searches for a single *closed* 
-// tour using the ordered moves function.
+//@tailrec
+/*
+def first_tour_heuristics(dim: Int, path: Path): Option[Path] = {
+
+  @tailrec
+  def aux(dim: Int, path: Path, moves: List[Pos]): Option[Path] = 
+  if (path.length == dim * dim) Some(path)
+  else
+    moves match {
+      case Nil => None
+      case x::xs => {
+        val r = first_tour_heuristics(dim, x::path)
+        if (r.isDefined) r else aux(dim, path, xs)
+      }    
+    }
+
+  aux(dim, path, ordered_moves(dim, path, path.head)) 
+}
+*/ 
 
-def first_closed_tour_heuristic(dim: Int, path: Path): Option[Path] = ...
+@tailrec
+def tour_on_mega_board(dim: Int, paths: List[Path]): Option[Path] = paths match {
+  case Nil => None
+  case (path::rest) =>
+    if (path.length == dim * dim) Some(path)
+    else tour_on_mega_board(dim, ordered_moves(dim, path, path.head).map(_::path) ::: rest)
+}
+
+
 
-//(3c) Same as (3b) but searches for *open* tours.
+/*
+def first_tour_heuristics(dim: Int, path: Path): Option[Path] = {
+  if (path.length == dim * dim) Some(path)
+  else
+    for (p <- ordered_moves(dim, path, path.head))
+      val r = first_tour_heuristics(dim, x::path)
+    //first(ordered_moves(dim, path, path.head), (x: Pos) => first_tour_heuristics(dim, x::path))
+    ordered_moves(dim, path, path.head).view.flatMap((x: Pos) => first_tour_heuristics(dim, x::path)).headOption
+}
+*/ 
 
-def first_tour_heuristic(dim: Int, path: Path): Option[Path] = ...
+/*
+for (dim <- 1 to 50) {
+  val t = first_tour_heuristics(dim, List((dim / 2, dim / 2)))
+  println(s"${dim} x ${dim}: " + (if (t == None) "" else { print_board(dim, t.get) ; "" }))
+}
+*/
+
+val dim = 70
+println(s"${dim} x ${dim}:")
+print_board(dim, time_needed(0, tour_on_mega_board(dim, List(List((0, 0)))).get))
+