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
}
}
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)
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))
// 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
}
*/
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 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
}
//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)
}