--- a/progs/knight2.scala Sat Nov 12 22:28:14 2016 +0000
+++ b/progs/knight2.scala Sun Nov 13 01:27:32 2016 +0000
@@ -1,41 +1,44 @@
import scala.util._
type Pos = (Int, Int)
-
-def print_board(n: Int)(steps: List[Pos]): Unit = {
- for (i <- 0 until n) {
- for (j <- 0 until n) {
- print(f"${steps.indexOf((i, j))}%3.0f ")
- }
- println
- }
- //readLine()
- System.exit(0)
-}
-
-def add_pair(x: Pos)(y: Pos) =
+def add_pair(x: Pos)(y: Pos): Pos =
(x._1 + y._1, x._2 + y._2)
-def is_legal(n: Int)(x: Pos) =
- 0 <= x._1 && 0 <= x._2 && x._1 < n && x._2 < n
+def is_legal(dim: Int, path: List[Pos])(x: Pos): Boolean =
+ 0 <= x._1 && 0 <= x._2 && x._1 < dim && x._2 < dim && !path.contains(x)
-def moves(n: Int)(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)).filter(is_legal(n))
+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: List[Pos], x: Pos): List[Pos] = {
+ moves(x).filter(is_legal(dim, path))
}
+
// non-circle tours
-def tour(n: Int)(steps: List[Pos]): List[List[Pos]] = {
- if (steps.length == n * n) // && moves(n)(steps.head).contains(steps.last))
- List(steps)
+/*
+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 <- moves(n)(steps.head).par;
- if (!steps.contains(x))) yield tour(n)(x :: steps)).toList.flatten
+ (for (x <- legal_moves(dim, path, path.head)) yield tour(dim, x::path)).flatten
+}
+*/
+
+def tour(dim: Int, path: List[Pos]): Int = {
+ if (path.length == dim * dim) 1
+ else
+ (for (x <- legal_moves(dim, path, path.head)) yield tour(dim, x::path)).sum
}
//val n = 8
val n = 6
println(s"number simple tours: n = $n")
-println(tour(n)(List((1,1))).distinct.size)
-//println((for (i <- 0 until n; j <- 0 until n) yield tour(n)(List((i, j)))).flatten.distinct.size)
+//println(tour(n, List((0, 0))))
+
+for (d <- 1 to 6) {
+ println(s"${d} x ${d} " + (for (i <- 0 until d; j <- 0 until d) yield tour(d, List((i, j)))).sum)
+}