progs/knight2.scala
author Christian Urban <urbanc@in.tum.de>
Wed, 09 Nov 2016 06:02:55 +0000
changeset 22 9830203b058d
parent 8 ab77f6006f1f
child 39 c6fe374a5fca
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 && moves(n)(steps.head).contains(steps.last)) List(steps)
  else 
    (for (x <- moves(n)(steps.head).par; if (!steps.contains(x))) yield tour(n)(x :: steps)).toList.flatten
}

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

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