--- 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] = ...
+