| 
4
 | 
     1  | 
import scala.util._
  | 
| 
 | 
     2  | 
  | 
| 
 | 
     3  | 
def print_board(n: Int)(steps: List[(Int, Int)]): Unit = synchronized {
 | 
| 
 | 
     4  | 
  for (i <- 0 until n) {
 | 
| 
 | 
     5  | 
    for (j <- 0 until n) {
 | 
| 
 | 
     6  | 
      print(f"${steps.indexOf((i, j))}%3.0f ")
 | 
| 
 | 
     7  | 
    }
  | 
| 
 | 
     8  | 
    println
  | 
| 
 | 
     9  | 
  } 
  | 
| 
 | 
    10  | 
  //readLine()
  | 
| 
 | 
    11  | 
  System.exit(0)
  | 
| 
 | 
    12  | 
}
  | 
| 
 | 
    13  | 
  | 
| 
 | 
    14  | 
def add_pair(x: (Int, Int))(y: (Int, Int)) = 
  | 
| 
 | 
    15  | 
  (x._1 + y._1, x._2 + y._2)
  | 
| 
 | 
    16  | 
  | 
| 
 | 
    17  | 
def is_legal(n: Int)(x: (Int, Int)) = 
  | 
| 
 | 
    18  | 
  0 <= x._1 && 0 <= x._2 && x._1 < n && x._2 < n
  | 
| 
 | 
    19  | 
  | 
| 
 | 
    20  | 
def moves(n: Int)(x: (Int, Int)): List[(Int, Int)] = {
 | 
| 
 | 
    21  | 
  List((1, 2),(2, 1),(2, -1),(1, -2),
  | 
| 
 | 
    22  | 
       (-1, -2),(-2, -1),(-2, 1),(-1, 2)).map(add_pair(x)).filter(is_legal(n))
  | 
| 
 | 
    23  | 
}
  | 
| 
 | 
    24  | 
  | 
| 
 | 
    25  | 
def ordered_moves(n: Int)(steps: List[(Int, Int)])(x : (Int, Int)): List[(Int, Int)] = 
  | 
| 
 | 
    26  | 
  moves(n)(x).sortBy((x: (Int, Int)) => moves(n)(x).filterNot(steps.contains(_)).length)
  | 
| 
 | 
    27  | 
  | 
| 
 | 
    28  | 
moves(8)(1,3)
  | 
| 
 | 
    29  | 
ordered_moves(8)(Nil)(1,3)
  | 
| 
 | 
    30  | 
ordered_moves(8)(List((2, 4), (2, 6)))(1,3)
  | 
| 
 | 
    31  | 
  | 
| 
 | 
    32  | 
// non-circle tour parallel
  | 
| 
 | 
    33  | 
def tour(n: Int)(steps: List[(Int, Int)]): Unit = {
 | 
| 
 | 
    34  | 
  if (steps.length ==  n * n && moves(n)(steps.head).contains(steps.last))
  | 
| 
 | 
    35  | 
    print_board(n)(steps)
  | 
| 
 | 
    36  | 
  else 
  | 
| 
 | 
    37  | 
    for (x <- ordered_moves(n)(steps)(steps.head).par; if (!steps.contains(x))) tour(n)(x :: steps)
  | 
| 
 | 
    38  | 
}
  | 
| 
 | 
    39  | 
  | 
| 
 | 
    40  | 
val n = 7
  | 
| 
 | 
    41  | 
println(s"circle tour parallel fast: n = $n")
  | 
| 
 | 
    42  | 
  | 
| 
 | 
    43  | 
val starts = for (i <- 0 until n; j <- 0 until n) yield (i, j)
  | 
| 
 | 
    44  | 
  | 
| 
 | 
    45  | 
starts.par.foreach((x:(Int, Int)) => tour(n)(List(x))) 
  |