Binary file cws/cw01.pdf has changed
Binary file cws/cw02.pdf has changed
--- a/cws/cw02.tex Tue Nov 15 23:08:09 2016 +0000
+++ b/cws/cw02.tex Wed Nov 16 14:37:18 2016 +0000
@@ -16,13 +16,23 @@
\section*{Coursework 7 (Scala, Knight's Tour)}
-This coursework is about searching and backtracking, and worth
-10\%. The first part is due on 23 November at 11pm; the second, more
-advanced part, is due on 30 November at 11pm. You are asked to
-implement Scala programs that solve various versions of the
+This coursework is worth 10\%. It is about searching and
+backtracking. The first part is due on 23 November at 11pm; the
+second, more advanced part, is due on 30 November at 11pm. You are
+asked to implement Scala programs that solve various versions of the
\textit{Knight's Tour Problem} on a chessboard. Make sure the files
you submit can be processed by just calling \texttt{scala
- <<filename.scala>>}.
+ <<filename.scala>>}.\bigskip
+
+\noindent
+\textbf{Important:} Do not use any mutable data structures in your
+submissions! They are not needed. This excluded the use of
+\texttt{ListBuffer}s, for example. Do not use \texttt{return} in your
+code! It has a different meaning in Scala, than in Java. Feel free to
+copy any code you need from files \texttt{knight1.scala},
+\texttt{knight2.scala} and \texttt{knight3.scala}. Make sure the
+functions you submit are defined on the ``top-level'' of Scala, not
+inside a class or object.
\subsection*{Disclaimer}
@@ -78,7 +88,8 @@
knight's tour is \underline{not} closed (it is open) because the last
step on field $(0, 4)$ is not within the reach of the first step on
$(4, 4)$. It turns out there is no closed knight's tour on a $5\times
-5$ board. But there are on a $6\times 6$ board and bigger, for example
+5$ board. But there are on a $6\times 6$ board and on bigger ones, for
+example
\chessboard[maxfield=e5,
pgfstyle= {[base,at={\pgfpoint{0pt}{-0.5ex}}]text},
@@ -146,15 +157,15 @@
markfields={f5, e6},
setpieces={Ng7, Nb2}]
-\subsection*{Part 1 (6 Marks)}
+\subsection*{Part 1 (7 Marks)}
You are asked to implement the knight's tour problem such that the
dimension of the board can be changed. Therefore most functions will
-take the dimension as an argument. The fun with this problem is that
-even for small chessbord dimensions it has already an incredably large
-search space---finding a tour is like finding a needle in a
-haystack. In the first task we want to see far we get with
-exhaustively exploring the complete search space for small
+take the dimension of the board as an argument. The fun with this
+problem is that even for small chessbord dimensions it has already an
+incredably large search space---finding a tour is like finding a
+needle in a haystack. In the first task we want to see how far we get
+with exhaustively exploring the complete search space for small
chessboards.\medskip
\noindent
@@ -183,9 +194,10 @@
\subsubsection*{Tasks (file knight1.scala)}
\begin{itemize}
-\item[(1a)] Implement a is-legal-move function that takes a dimension, a path
-and a position as argument and tests whether the position is inside
-the board and not yet element in the path. \hfill[1 Mark]
+\item[(1a)] Implement an is-legal-move function that takes a
+ dimension, a path and a position as argument and tests whether the
+ position is inside the board and not yet element in the
+ path. \hfill[1 Mark]
\item[(1b)] Implement a legal-moves function that calculates for a
position all legal onward moves. If the onward moves are
@@ -193,15 +205,15 @@
``12-oclock'' following in clockwise order. For example on an
$8\times 8$ board for a knight on position $(2, 2)$ and otherwise
empty board, the legal-moves function should produce the onward
- positions
+ positions in this order:
\begin{center}
\texttt{List((3,4), (4,3), (4,1), (3,0), (1,0), (0,1), (0,3), (1,4))}
\end{center}
- in this order. If the board is not empty, then maybe some of the
- moves need to be filtered out from this list. For a knight on field
- $(7, 7)$ and an empty board, the legal moves are
+ If the board is not empty, then maybe some of the moves need to be
+ filtered out from this list. For a knight on field $(7, 7)$ and an
+ empty board, the legal moves are
\begin{center}
\texttt{List((6,5), (5,6))}
@@ -210,16 +222,16 @@
\item[(1c)] Implement two recursive functions (count-tours and
enum-tours). They each take a dimension and a path as
- arguments. They exhaustively search for \underline{\bf open} tours
- starting from the given path. The first function counts all possible
- open tours (there can be none for certain board sizes) and the second
+ arguments. They exhaustively search for {\bf open} tours starting
+ from the given path. The first function counts all possible open
+ tours (there can be none for certain board sizes) and the second
collects all open tours in a list of paths.\hfill[2 Marks]
\end{itemize}
\noindent \textbf{Test data:} For the marking, the functions in (1c)
-will be called with board sizes up to $5 \times 5$. If you only search
-for open tours on $5 \times 5$ board starting from field $(0, 0)$,
-there are 304 of them. If you try out every field of a $5 \times
+will be called with board sizes up to $5 \times 5$. If you search
+for open tours on a $5 \times 5$ board starting only from field $(0, 0)$,
+there are 304 of tours. If you try out every field of a $5 \times
5$-board as a starting field and add up all open tours, you obtain
1728. A $6\times 6$ board is already too large to be searched
exhaustively.\footnote{For your interest, the number of open tours on
@@ -231,8 +243,9 @@
\begin{itemize}
\item[(2a)] Implement a first-function. This function takes a list of
positions and a function $f$ as arguments. The function $f$ takes a
- position as argument and produces an optional path. The idea behind
- the first-function is as follows:
+ position as argument and produces an optional path. So its type is
+ \texttt{Pos => Option[Path]}. The idea behind the first-function is
+ as follows:
\[
\begin{array}{lcl}
@@ -245,12 +258,12 @@
\]
\noindent That is, we want to find the first position where the
- result of $f$ is not \texttt{None}.\newline\mbox{}\hfill[1 Mark]
+ result of $f$ is not \texttt{None}, if there is one.\mbox{}\hfill[1 Mark]
-\item[(2b)] Implement a first-tour function. Using the first-function
- from (2a), search recursively for an open tour. As there might not
- be such a tour at all, the first-tour function needs to return an
- \texttt{Option[Path]}.\hfill[2 Marks]
+\item[(2b)] Implement a first-tour function that uses the
+ first-function from (2a), and searches recursively for an open tour.
+ As there might not be such a tour at all, the first-tour function
+ needs to return an \texttt{Option[Path]}.\hfill[2 Marks]
\end{itemize}
\noindent
@@ -258,13 +271,13 @@
sizes of up to $8 \times 8$.
-\subsection*{Part 2 (4 Marks)}
+\subsection*{Part 2 (3 Marks)}
As you should have seen in Part 1, a naive search for open tours
-beyond $8 \times 8$ boards and also for searching for closed tours
+beyond $8 \times 8$ boards and also searching for closed tours
takes too much time. There is a heuristic (called Warnsdorf's rule)
-that can speed up finding a tour. This heuristice states that a knight
-is moved so that it always proceeds to the square from which the
+that can speed up finding a tour. This heuristic states that a knight
+is moved so that it always proceeds to the field from which the
knight will have the \underline{fewest} onward moves. For example for
a knight on field $(1, 3)$, the field $(0, 1)$ has the fewest possible
onward moves, namely 2.
@@ -281,7 +294,7 @@
\noindent
Warnsdorf's rule states that the moves on the board above sould be
-tried out in the order
+tried in the order
\[
(0, 1), (0, 5), (2, 1), (2, 5), (3, 4), (3, 2)
@@ -295,11 +308,20 @@
\subsubsection*{Tasks (file knight3.scala)}
\begin{itemize}
-\item[(3a)] orderered-moves
+\item[(3a)] Write a function ordered-moves 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 (in order to be tried out first).
+
+\item[(3b)] Implement a first-closed-tour-heuristic function that searches for a
+ \textbf{closed} tour on a $6\times 6$ board. It should use the
+ first-function from (2a) and tries out onwards moves according to
+ the ordered-moves function from (3a). It is more likely to find
+ a solution when started in the middle of the board (that is
+ position $(dimension / 2, dimension / 2)$).
-\item[(3b)] first-closed tour heuristics; up to $6\times 6$
-
-\item[(3c)] first tour heuristics; up to $50\times 50$
+\item[(3c)] Implement a first-tour-heuristic function for boards up to $50\times 50$.
+ It is the same function as in (3b) but searches for \textbf{open} tours.
\end{itemize}
\end{document}
--- a/progs/collatz_sol2.scala Tue Nov 15 23:08:09 2016 +0000
+++ b/progs/collatz_sol2.scala Wed Nov 16 14:37:18 2016 +0000
@@ -15,7 +15,7 @@
// an alternative that calculates the steps directly
-def collatz1(n: Long): Int =
+def collatz1(n: Long): Long =
if (n == 1) 1 else
if (n % 2 == 0) (1 + collatz1(n / 2)) else
(1 + collatz1(3 * n + 1))
@@ -37,13 +37,15 @@
// upto 1 million.
def collatz_max(bnd: Long): (Long, Long) = {
- (1L to bnd).view.map((i) => (collatz2(i, 1), i)).maxBy(_._1)
+ (1L to bnd).view.map((i) => (collatz1(i), i)).maxBy(_._1)
}
// some testing harness
//val bnds = List(10, 100, 1000, 10000, 100000, 1000000)
-val bnds = List(10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000)
+val bnds = List(10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 2000000000)
+
+
for (bnd <- bnds) {
val (steps, max) = collatz_max(bnd)
--- a/progs/knight1.scala Tue Nov 15 23:08:09 2016 +0000
+++ b/progs/knight1.scala Wed Nov 16 14:37:18 2016 +0000
@@ -1,76 +1,36 @@
-import scala.util._
+// Part 1 about finding and counting Knight's tours
+//==================================================
-class Computation[A,B](value: A, function: A => B) {
- lazy val result = function(value)
-}
+type Pos = (Int, Int) // a position on a chessboard
+type Path = List[Pos] // a path...a list of positions
+
+//(1a) Complete the function that tests whether the position
+// is inside the board and not yet element in the path.
+
+def is_legal(dim: Int, path: Path)(x: Pos): Boolean = ...
-def print_board(n: Int)(steps: List[(Int, Int)]): Unit = {
- println
- for (i <- 0 until n) {
- for (j <- 0 until n) {
- print(f"${steps.indexOf((i, j))}%3.0f ")
- }
- println
- }
-}
-
-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)(steps: List[(Int, Int)])(x: (Int, Int)): List[(Int, Int)] = {
- List((1, 2),(2, 1),(2, -1),(1, -2),
- (-1, -2),(-2, -1),(-2, 1),(-1, 2)).map(add_pair(x)).filter(is_legal(n)).filterNot(steps.contains(_))
-}
-
-def ordered_moves(n: Int)(steps: List[(Int, Int)])(x : (Int, Int)): List[(Int, Int)] =
- moves(n)(steps)(x).sortBy(moves(n)(steps)(_).length)
-
-moves(8)(Nil)(1,3)
-ordered_moves(8)(Nil)(1,3)
-ordered_moves(8)(List((2, 4), (2, 6)))(1,3)
+//(1b) Complete the function that calculates for a position
+// all legal onward moves that are not already in the path.
+// The moves should be ordered in a "clockwise" order.
+
+def legal_moves(dim: Int, path: Path, x: Pos): List[Pos] = ...
-def first[A, B](xs: List[A], f: A => Set[B]): Set[B] = xs match {
- case Nil => Set()
- case x::xs => {
- val result = f(x)
- if (result == Set()) first(xs, f) else result
- }
-}
-
-// non-circular tour
-def tour(n: Int)(steps: List[(Int, Int)]): Option[List[(Int, Int)]] = {
- if (steps.length == n * n) Some(steps)
- else
- { val list = moves(n)(steps)(steps.head) map (x => new Computation(x, ((x:(Int, Int)) => tour(n)(x::steps))))
- val found = list.par find (_.result.isDefined)
- found map (_.result.get)
- }
-}
-
-val n = 6
-println(s"simple tour: n = $n")
-
-val starts = for (i <- (0 until n).toList;
- j <- (0 until n).toList) yield new Computation ((i, j), ((x:(Int, Int)) => tour(n)(x::Nil)))
-
-val found = starts.par find (_.result.isDefined)
-print_board(n)((found map (_.result.get)).get)
-
-//for measuring time
-def time_needed[T](i: Int, code: => T) = {
- val start = System.nanoTime()
- for (j <- 1 to i) code
- val end = System.nanoTime()
- (end - start)/(i * 1.0e9)
-}
-
-//for (i <- 1 to 20) {
-// println(i + ": " + "%.5f".format(time_needed(2, matches(EVIL1(i), "a" * i))))
-//}
+//assert(legal_moves(8, Nil, (2,2)) ==
+// List((3,4), (4,3), (4,1), (3,0), (1,0), (0,1), (0,3), (1,4)))
+//assert(legal_moves(8, Nil, (7,7)) == List((6,5), (5,6)))
+//assert(legal_moves(8, List((4,1), (1,0)), (2,2)) ==
+// List((3,4), (4,3), (3,0), (0,1), (0,3), (1,4)))
+//assert(legal_moves(8, List((6,6)), (7,7)) == List((6,5), (5,6)))
+//(1c) Complement the two recursive functions below.
+// They exhaustively search for open tours starting from the
+// given path. The first function counts all possible open tours,
+// and the second collects all open tours in a list of paths.
+def count_tours(dim: Int, path: Path): Int = ...
+
+def enum_tours(dim: Int, path: Path): List[Path] = ...
+
+
--- a/progs/knight1_sol.scala Tue Nov 15 23:08:09 2016 +0000
+++ b/progs/knight1_sol.scala Wed Nov 16 14:37:18 2016 +0000
@@ -27,9 +27,12 @@
def legal_moves(dim: Int, path: Path, x: Pos): List[Pos] =
moves(x).filter(is_legal(dim, path))
-legal_moves(8, Nil, (2,2))
-legal_moves(8, Nil, (7,7))
-
+assert(legal_moves(8, Nil, (2,2)) ==
+ List((3,4), (4,3), (4,1), (3,0), (1,0), (0,1), (0,3), (1,4)))
+assert(legal_moves(8, Nil, (7,7)) == List((6,5), (5,6)))
+assert(legal_moves(8, List((4,1), (1,0)), (2,2)) ==
+ List((3,4), (4,3), (3,0), (0,1), (0,3), (1,4)))
+assert(legal_moves(8, List((6,6)), (7,7)) == List((6,5), (5,6)))
def count_tours(dim: Int, path: Path): Int = {
if (path.length == dim * dim) 1
--- a/progs/knight2.scala Tue Nov 15 23:08:09 2016 +0000
+++ b/progs/knight2.scala Wed Nov 16 14:37:18 2016 +0000
@@ -1,78 +1,21 @@
-
-type Pos = (Int, Int)
-type Path = List[Pos]
-
-def print_board(dim: Int, path: Path): Unit = {
- println
- for (i <- 0 until dim) {
- for (j <- 0 until dim) {
- print(f"${path.indexOf((i, j))}%3.0f ")
- }
- println
- }
-}
-
+// Part 2 about finding a single tour for a board
+//================================================
-def add_pair(x: Pos)(y: Pos): Pos =
- (x._1 + y._1, x._2 + y._2)
-
-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)
+// copy any function you need from file knight1.scala
-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))
-
+type Pos = (Int, Int) // a position on a chessboard
+type Path = List[Pos] // a path...a list of positions
-// non-circle tours
-/*
-def tour(dim: Int, path: List[Pos]): List[List[Pos]] = {
- if (path.length == dim * dim) // && moves(n)(path.head).contains(path.last))
- List(path)
- else
- (for (x <- legal_moves(dim, path, path.head)) yield tour(dim, x::path)).flatten
-}
-*/
+//(2a) Implement a first-function that finds the first
+// element, say x, in the list xs where f is not None.
+// In that case return f(x), otherwise none.
-def tour(dim: Int, path: Path): Int = {
- if (path.length == dim * dim) 1
- else
- (for (x <- legal_moves(dim, path, path.head) yield tour(dim, x::path))).sum
-}
-
-
-def dtour(dim: Int): List[List[Pos]] = {
- var counter = 100000000
+def first(xs: List[Pos], f: Pos => Option[Path]): Option[Path] = ...
- def etour(dim: Int, path: List[Pos]): List[List[Pos]] = {
- counter = counter - 1
- if (counter <= 0) List() else
- if (path.length == dim * dim) List(path)
- else
- (for (x <- legal_moves(dim, path, path.head)) yield etour(dim, x::path)).flatten
- }
-
- (for (i <- (0 until dim).toList;
- j <- (0 until dim).toList) yield etour(dim, List((i, j)))).flatten
-}
-
-
+//(2b) Implement a function that uses the first-function for
+// trying out onward moves, and searches recursively for an
+// *open* tour on a dim * dim-board.
-//val n = 8
-val n = 5
-println(s"number simple tours: n = $n")
-
-//println(etour(n, List((0, 0))).size)
-
-
-
-for (d <- 9 to 9) {
- println(s"${d} x ${d} " + dtour(d).length)
-}
-
-
+def first_tour(dim: Int, path: Path): Option[Path] = ...
+
--- a/progs/knight2_sol.scala Tue Nov 15 23:08:09 2016 +0000
+++ b/progs/knight2_sol.scala Wed Nov 16 14:37:18 2016 +0000
@@ -1,9 +1,8 @@
// Part 2 about finding a single tour for a board
//================================================
-
-type Pos = (Int, Int)
-type Path = List[Pos]
+type Pos = (Int, Int) // a position on a chessboard
+type Path = List[Pos] // a path...a list of positions
def print_board(dim: Int, path: Path): Unit = {
println
--- a/progs/knight3.scala Tue Nov 15 23:08:09 2016 +0000
+++ b/progs/knight3.scala Wed Nov 16 14:37:18 2016 +0000
@@ -1,45 +1,65 @@
-import scala.util._
+// Part 3 about finding a single tour using the Warnsdorf Rule
+//=============================================================
+
-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))}%3.0f ")
+type Pos = (Int, Int)
+type Path = List[Pos]
+
+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))}%3.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)] = {
- List((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 ordered_moves(n: Int)(steps: List[(Int, Int)])(x : (Int, Int)): List[(Int, Int)] =
- moves(n)(x).sortBy((x: (Int, Int)) => moves(n)(x).filterNot(steps.contains(_)).length)
+def add_pair(x: Pos)(y: Pos): Pos =
+ (x._1 + y._1, x._2 + y._2)
-moves(8)(1,3)
-ordered_moves(8)(Nil)(1,3)
-ordered_moves(8)(List((2, 4), (2, 6)))(1,3)
+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))
-// non-circle tour parallel
-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)
+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)
+
+
+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)
+ }
}
-val n = 7
-println(s"circle tour parallel: n = $n")
+
+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))
+}
+
+for (dim <- 1 to 6) {
+ val t = 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) ; "" }))
+}
-val starts = for (i <- 0 until n; j <- 0 until n) yield (i, j)
-starts.par.foreach((x:(Int, Int)) => tour(n)(List(x)))
+def first_tour_heuristics(dim: Int, path: Path): Option[Path] = {
+ if (path.length == dim * dim) Some(path)
+ else
+ first(ordered_moves(dim, path, path.head), (x: Pos) => first_tour_heuristics(dim, x::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) ; "" }))
+}
--- a/progs/knight3_sol.scala Tue Nov 15 23:08:09 2016 +0000
+++ b/progs/knight3_sol.scala Wed Nov 16 14:37:18 2016 +0000
@@ -1,65 +1,24 @@
-// Part 2 about finding a single tour for a board
-//================================================
-
-
-type Pos = (Int, Int)
-type Path = List[Pos]
+// Part 3 about finding a single tour using the Warnsdorf Rule
+//=============================================================
-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))}%3.0f ")
- }
- println
- }
-}
-
-def add_pair(x: Pos)(y: Pos): Pos =
- (x._1 + y._1, x._2 + y._2)
+// copy any function you need from files knight1.scala and
+// knight2.scala
-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)
+type Pos = (Int, Int) // a position on a chessboard
+type Path = List[Pos] // a path...a list of positions
+//(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.
-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_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))
-}
+def ordered_moves(dim: Int, path: Path, x: Pos): List[Pos] = ..
-for (dim <- 1 to 7) {
- val t = 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.
-def first_tour_heuristics(dim: Int, path: Path): Option[Path] = {
- if (path.length == dim * dim) Some(path)
- else
- first(ordered_moves(dim, path, path.head), (x: Pos) => first_tour_heuristics(dim, x::path))
-}
+def first_closed_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) ; "" }))
-}
+//(3c) Sama as (3b) but searches for *open* tours.
+
+def first_tour_heuristic(dim: Int, path: Path): Option[Path] = ...