import scala.util._
class Computation[A,B](value: A, function: A => B) {
lazy val result = function(value)
}
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)
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))))
//}