progs/knight2.scala
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Sun, 13 Nov 2016 11:56:06 +0000
changeset 43 ba4081c70de4
parent 42 a5106bc13db6
child 44 9cfa37c91444
permissions -rw-r--r--
updated

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

def add_pair(x: Pos)(y: Pos): Pos = 
  (x._1 + y._1, x._2 + y._2)

def is_legal(dim: Int, path: List[Pos])(x: Pos): Boolean = 
  0 <= x._1 && 0 <= x._2 && x._1 < dim && x._2 < dim && !path.contains(x)

def moves(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))
}

def legal_moves(dim: Int, path: List[Pos], x: Pos): List[Pos] = {
  moves(x).filter(is_legal(dim, path))
}


// non-circle tours
/*
def tour(dim: Int, path: List[Pos]): List[List[Pos]] = {
  if (path.length ==  dim * dim) // && moves(n)(path.head).contains(path.last)) 
    List(path)
  else 
    (for (x <- legal_moves(dim, path, path.head)) yield tour(dim, x::path)).flatten
}
*/

def tour(dim: Int, path: List[Pos]): Int = {
  if (path.length == dim * dim) 1
  else 
    (for (x <- legal_moves(dim, path, path.head).par) yield tour(dim, x::path)).sum
}

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

println(tour(n, List((0, 0))))

/*
for (d <- 1 to 6) {
  println(s"${d} x ${d} " + (for (i <- 0 until d; j <- 0 until d) yield tour(d, List((i, j)))).sum)
} 
*/