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