1 // Part 4 about finding a single tour on "mutilated" chessboards |
1 // Part 4 about finding a single tour on "mutilated" chessboards |
2 //============================================================== |
2 //============================================================== |
3 |
3 |
4 object M4d { // for preparing the jar |
4 object M4d { |
|
5 |
|
6 // !!! Copy any function you need from file knight1.scala !!! |
|
7 // !!! or knight2.scala or knight3.scala !!! |
|
8 // |
|
9 // If you need any auxiliary function, feel free to |
|
10 // implement it, but do not make any changes to the |
|
11 // templates below. |
5 |
12 |
6 type Pos = (Int, Int) |
13 type Pos = (Int, Int) |
7 type Path = List[Pos] |
14 type Path = List[Pos] |
8 |
15 |
9 def print_board(dim: Int, path: Path): Unit = { |
16 def print_board(dim: Int, path: Path): Unit = { |
14 } |
21 } |
15 println() |
22 println() |
16 } |
23 } |
17 } |
24 } |
18 |
25 |
19 def add_pair(x: Pos, y: Pos): Pos = |
26 // ADD YOUR CODE BELOW |
20 (x._1 + y._1, x._2 + y._2) |
27 //====================== |
21 |
28 |
22 def is_legal(dim: Int, path: Path, x: Pos): Boolean = |
29 // (10) |
23 0 <= x._1 && 0 <= x._2 && x._1 < dim && x._2 < dim && !path.contains(x) |
30 def one_tour_pred(dim: Int, path: Path, n: Int, pred: Pos => Boolean): Option[Path] = ??? |
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 |
|
33 |
|
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) |
|
51 |
31 |
52 |
32 |
53 } |
33 } |