diff -r 575a5c07c7fe -r f31c22f4f104 progs/knight3.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/knight3.scala Wed Nov 02 13:22:40 2016 +0000 @@ -0,0 +1,45 @@ +import scala.util._ + +def print_board(n: Int)(steps: List[(Int, Int)]): 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: (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)(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)) +} + +def ordered_moves(n: Int)(steps: List[(Int, Int)])(x : (Int, Int)): List[(Int, Int)] = + moves(n)(x).sortBy((x: (Int, Int)) => moves(n)(x).filterNot(steps.contains(_)).length) + +moves(8)(1,3) +ordered_moves(8)(Nil)(1,3) +ordered_moves(8)(List((2, 4), (2, 6)))(1,3) + +// non-circle tour parallel +def tour(n: Int)(steps: List[(Int, Int)]): Unit = { + if (steps.length == n * n && moves(n)(steps.head).contains(steps.last)) + print_board(n)(steps) + else + for (x <- moves(n)(steps.head).par; if (!steps.contains(x))) tour(n)(x :: steps) +} + +val n = 7 +println(s"circle tour parallel: n = $n") + +val starts = for (i <- 0 until n; j <- 0 until n) yield (i, j) + +starts.par.foreach((x:(Int, Int)) => tour(n)(List(x)))