progs/knight2_sol.scala
changeset 45 8399976b77fe
child 50 9891c9fac37e
equal deleted inserted replaced
44:9cfa37c91444 45:8399976b77fe
       
     1 // Part 2 about finding a single tour for a board
       
     2 //================================================
       
     3 
       
     4 
       
     5 type Pos = (Int, Int)
       
     6 type Path = List[Pos]
       
     7 
       
     8 def print_board(dim: Int, path: Path): Unit = {
       
     9   println
       
    10   for (i <- 0 until dim) {
       
    11     for (j <- 0 until dim) {
       
    12       print(f"${path.reverse.indexOf((i, j))}%3.0f ")
       
    13     }
       
    14     println
       
    15   } 
       
    16 }
       
    17 
       
    18 def add_pair(x: Pos)(y: Pos): Pos = 
       
    19   (x._1 + y._1, x._2 + y._2)
       
    20 
       
    21 def is_legal(dim: Int, path: Path)(x: Pos): Boolean = 
       
    22   0 <= x._1 && 0 <= x._2 && x._1 < dim && x._2 < dim && !path.contains(x)
       
    23 
       
    24 def moves(x: Pos): List[Pos] = 
       
    25   List(( 1,  2),( 2,  1),( 2, -1),( 1, -2),
       
    26        (-1, -2),(-2, -1),(-2,  1),(-1,  2)).map(add_pair(x))
       
    27 
       
    28 def legal_moves(dim: Int, path: Path, x: Pos): List[Pos] = 
       
    29   moves(x).filter(is_legal(dim, path))
       
    30 
       
    31 
       
    32 def first(xs: List[Pos], f: Pos => Option[Path]): Option[Path] = xs match {
       
    33   case Nil => None
       
    34   case x::xs => {
       
    35     val result = f(x)
       
    36     if (result.isDefined) result else first(xs, f)
       
    37   }
       
    38 }
       
    39 
       
    40 
       
    41 def first_tour(dim: Int, path: Path): Option[Path] = {
       
    42   if (path.length == dim * dim) Some(path)
       
    43   else
       
    44     first(legal_moves(dim, path, path.head), (x: Pos) => first_tour(dim, x::path))
       
    45 }
       
    46 
       
    47 for (dim <- 1 to 8) {
       
    48   val t = first_tour(dim, List((0, 0)))
       
    49   println(s"${dim} x ${dim} " + (if (t == None) "" else { print_board(dim, t.get) ; "" }))
       
    50 }
       
    51