| 145 |      1 | // Part 2 about finding a single tour for a board
 | 
|  |      2 | //================================================
 | 
|  |      3 | 
 | 
|  |      4 | object CW7b {
 | 
|  |      5 | 
 | 
|  |      6 | type Pos = (Int, Int)    // a position on a chessboard 
 | 
|  |      7 | type Path = List[Pos]    // a path...a list of positions
 | 
|  |      8 | 
 | 
|  |      9 | def print_board(dim: Int, path: Path): Unit = {
 | 
|  |     10 |   println
 | 
|  |     11 |   for (i <- 0 until dim) {
 | 
|  |     12 |     for (j <- 0 until dim) {
 | 
|  |     13 |       print(f"${path.reverse.indexOf((i, j))}%3.0f ")
 | 
|  |     14 |     }
 | 
|  |     15 |     println
 | 
|  |     16 |   } 
 | 
|  |     17 | }
 | 
|  |     18 | 
 | 
|  |     19 | def add_pair(x: Pos)(y: Pos): Pos = 
 | 
|  |     20 |   (x._1 + y._1, x._2 + y._2)
 | 
|  |     21 | 
 | 
|  |     22 | def is_legal(dim: Int, path: Path)(x: Pos): Boolean = 
 | 
|  |     23 |   0 <= x._1 && 0 <= x._2 && x._1 < dim && x._2 < dim && !path.contains(x)
 | 
|  |     24 | 
 | 
|  |     25 | def moves(x: Pos): List[Pos] = 
 | 
|  |     26 |   List(( 1,  2),( 2,  1),( 2, -1),( 1, -2),
 | 
|  |     27 |        (-1, -2),(-2, -1),(-2,  1),(-1,  2)).map(add_pair(x))
 | 
|  |     28 | 
 | 
|  |     29 | def legal_moves(dim: Int, path: Path, x: Pos): List[Pos] = 
 | 
|  |     30 |   moves(x).filter(is_legal(dim, path))
 | 
|  |     31 | 
 | 
|  |     32 | 
 | 
|  |     33 | def first(xs: List[Pos], f: Pos => Option[Path]): Option[Path] = xs match {
 | 
|  |     34 |   case Nil => None
 | 
|  |     35 |   case x::xs => {
 | 
|  |     36 |     val result = f(x)
 | 
|  |     37 |     if (result.isDefined) result else first(xs, f)
 | 
|  |     38 |   }
 | 
|  |     39 | }
 | 
|  |     40 | 
 | 
|  |     41 | //first(List((1, 0),(2, 0),(3, 0),(4, 0)), (x => if (x._1 > 3) Some(List(x)) else None))
 | 
|  |     42 | //first(List((1, 0),(2, 0),(3, 0)), (x => if (x._1 > 3) Some(List(x)) else None))
 | 
|  |     43 | 
 | 
|  |     44 | def first_tour(dim: Int, path: Path): Option[Path] = {
 | 
|  |     45 |   if (path.length == dim * dim) Some(path)
 | 
|  |     46 |   else
 | 
|  |     47 |     first(legal_moves(dim, path, path.head), (x: Pos) => first_tour(dim, x::path))
 | 
|  |     48 | }
 | 
|  |     49 | 
 | 
|  |     50 | /* 
 | 
|  |     51 | val ts1 = first_tour(8, List((0, 0))).get
 | 
|  |     52 |   assert(correct_urban(8)(ts1) == true)
 | 
|  |     53 | 
 | 
|  |     54 | val ts2 = first_tour(4, List((0, 0)))
 | 
|  |     55 | assert(ts2 == None)  
 | 
|  |     56 | 
 | 
|  |     57 | print_board(8, first_tour(8, List((0, 0))).get)
 | 
|  |     58 | */
 | 
|  |     59 | 
 | 
|  |     60 | }
 | 
|  |     61 | 
 |