progs/knight.scala
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Mon, 31 Oct 2016 10:41:23 +0000
changeset 1 b595d654cb2d
parent 0 02f53f76f828
child 2 e0ec73c462c7
permissions -rw-r--r--
typo



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))}%2.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 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 = 6

println("started")
for (i <- 0 until n; j <- 0 until n) tour(n)(List((i, j)))
println("finished")