progs/knight.scala
changeset 0 02f53f76f828
child 1 b595d654cb2d
equal deleted inserted replaced
-1:000000000000 0:02f53f76f828
       
     1 
       
     2 
       
     3 def print_board(n: Int)(steps: List[(Int, Int)]): Unit = {
       
     4   for (i <- 0 until n) {
       
     5     for (j <- 0 until n) {
       
     6       print(f"${steps.indexOf((i, j))}%2.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   Set((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 tour(n: Int)(steps: List[(Int, Int)]): Unit = {
       
    26   if (steps.length ==  n * n && moves(n)(steps.head).contains(steps.last))
       
    27     print_board(n)(steps)
       
    28   else 
       
    29     for (x <- moves(n)(steps.head).par; if (!steps.contains(x))) tour(n)(x :: steps)
       
    30 }
       
    31 
       
    32 val n = 6
       
    33 
       
    34 println("started")
       
    35 for (i <- 0 until n; j <- 0 until n) tour(n)(List((i, j)))
       
    36 println("finished")