progs/knight2.scala
author Christian Urban <urbanc@in.tum.de>
Thu, 03 Nov 2016 00:53:53 +0000
changeset 6 aae256985251
parent 5 c1e6123d02f4
child 7 7a5a29a32568
permissions -rw-r--r--
updated

import scala.util._
type Pos = (Int, Int)


def print_board(n: Int)(steps: List[Pos]): 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: Pos)(y: Pos) = 
  (x._1 + y._1, x._2 + y._2)

def is_legal(n: Int)(x: Pos) = 
  0 <= x._1 && 0 <= x._2 && x._1 < n && x._2 < n

def moves(n: Int)(x: Pos): List[Pos] = {
  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))
}

// non-circle tours
def tour(n: Int)(steps: List[Pos]): List[List[Pos]] = {
  if (steps.length ==  n * n) List(steps)
  else 
    (for (x <- moves(n)(steps.head); if (!steps.contains(x))) yield tour(n)(x :: steps)).flatten
}

//val n = 8
val n = 6
println(s"number simple tours: n = $n")

println((for (i <- 0 until n; j <- 0 until n) yield tour(n)(List((i, j)))).flatten.distinct.size)