430
|
1 |
// Part 4 about finding a single tour on "mutilated" chessboards
|
|
2 |
//==============================================================
|
|
3 |
|
432
|
4 |
object M4d { // for preparing the jar
|
213
|
5 |
|
|
6 |
type Pos = (Int, Int)
|
|
7 |
type Path = List[Pos]
|
|
8 |
|
|
9 |
def print_board(dim: Int, path: Path): Unit = {
|
347
|
10 |
println()
|
213
|
11 |
for (i <- 0 until dim) {
|
|
12 |
for (j <- 0 until dim) {
|
|
13 |
print(f"${path.reverse.indexOf((i, j))}%4.0f ")
|
|
14 |
}
|
347
|
15 |
println()
|
213
|
16 |
}
|
|
17 |
}
|
|
18 |
|
432
|
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 |
import scala.annotation.tailrec
|
213
|
33 |
|
432
|
34 |
@tailrec
|
|
35 |
def first(xs: List[Pos], f: Pos => Option[Path]): Option[Path] = xs match {
|
|
36 |
case Nil => None
|
|
37 |
case x::xs => {
|
|
38 |
val result = f(x)
|
|
39 |
if (result.isDefined) result else first(xs, f)
|
|
40 |
}
|
|
41 |
}
|
|
42 |
|
|
43 |
|
|
44 |
def one_tour_pred(dim: Int, path: Path, n: Int, pred: Pos => Boolean): Option[Path] = {
|
|
45 |
if (path.length == n) Some(path)
|
|
46 |
else
|
|
47 |
first(legal_moves(dim, path, path.head).filter(pred), (x: Pos) => one_tour_pred(dim, x::path, n, pred))
|
|
48 |
}
|
|
49 |
|
|
50 |
//print_board(8, one_tour_pred(8, List((0, 0)), 40, x => x._1 < 5).get)
|
213
|
51 |
|
|
52 |
|
|
53 |
}
|