|
1 // Main Part 4 about finding Knight's tours |
|
2 //========================================== |
|
3 |
|
4 |
|
5 object M4a { |
|
6 |
|
7 // If you need any auxiliary functions, feel free to |
|
8 // implement them, but do not make any changes to the |
|
9 // templates below. Also have a look whether the functions |
|
10 // at the end of the file are of any help. |
|
11 |
|
12 type Pos = (Int, Int) // a position on a chessboard |
|
13 type Path = List[Pos] // a path...a list of positions |
|
14 |
|
15 // ADD YOUR CODE BELOW |
|
16 //====================== |
|
17 |
|
18 |
|
19 |
|
20 //(1) |
|
21 def is_legal(dim: Int, path: Path, x: Pos) : Boolean = ??? |
|
22 |
|
23 |
|
24 //(2) |
|
25 def legal_moves(dim: Int, path: Path, x: Pos) : List[Pos] = ??? |
|
26 |
|
27 |
|
28 //some testcases |
|
29 // |
|
30 //assert(legal_moves(8, Nil, (2,2)) == |
|
31 // List((3,4), (4,3), (4,1), (3,0), (1,0), (0,1), (0,3), (1,4))) |
|
32 //assert(legal_moves(8, Nil, (7,7)) == List((6,5), (5,6))) |
|
33 //assert(legal_moves(8, List((4,1), (1,0)), (2,2)) == |
|
34 // List((3,4), (4,3), (3,0), (0,1), (0,3), (1,4))) |
|
35 //assert(legal_moves(8, List((6,6)), (7,7)) == List((6,5), (5,6))) |
|
36 |
|
37 |
|
38 // (3) |
|
39 def count_tours(dim: Int, path: Path) : Int = ??? |
|
40 |
|
41 def enum_tours(dim: Int, path: Path) : List[Path] = ??? |
|
42 |
|
43 // (4) |
|
44 def first(xs: List[Pos], f: Pos => Option[Path]) : Option[Path] = ??? |
|
45 |
|
46 |
|
47 // testcases |
|
48 // |
|
49 //def foo(x: (Int, Int)) = if (x._1 > 3) Some(List(x)) else None |
|
50 // |
|
51 //first(List((1, 0),(2, 0),(3, 0),(4, 0)), foo) // Some(List((4,0))) |
|
52 //first(List((1, 0),(2, 0),(3, 0)), foo) // None |
|
53 |
|
54 |
|
55 //(5) |
|
56 def first_tour(dim: Int, path: Path) : Option[Path] = ??? |
|
57 |
|
58 |
|
59 |
|
60 /* Helper functions |
|
61 |
|
62 |
|
63 // for measuring time |
|
64 def time_needed[T](code: => T) : T = { |
|
65 val start = System.nanoTime() |
|
66 val result = code |
|
67 val end = System.nanoTime() |
|
68 println(f"Time needed: ${(end - start) / 1.0e9}%3.3f secs.") |
|
69 result |
|
70 } |
|
71 |
|
72 // can be called for example with |
|
73 // |
|
74 // time_needed(count_tours(dim, List((0, 0)))) |
|
75 // |
|
76 // in order to print out the time that is needed for |
|
77 // running count_tours |
|
78 |
|
79 |
|
80 // for printing a board |
|
81 def print_board(dim: Int, path: Path): Unit = { |
|
82 println() |
|
83 for (i <- 0 until dim) { |
|
84 for (j <- 0 until dim) { |
|
85 print(f"${path.reverse.indexOf((j, dim - i - 1))}%3.0f ") |
|
86 } |
|
87 println() |
|
88 } |
|
89 } |
|
90 |
|
91 |
|
92 */ |
|
93 |
|
94 } |