|
1 import scala.util._ |
|
2 |
|
3 def print_board(n: Int)(steps: List[(Int, Int)]): Unit = { |
|
4 for (i <- 0 until n) { |
|
5 for (j <- 0 until n) { |
|
6 print(f"${steps.indexOf((i, j))}%3.0f ") |
|
7 } |
|
8 println |
|
9 } |
|
10 //readLine() |
|
11 //System.exit(0) |
|
12 throw new Exception("\n") |
|
13 } |
|
14 |
|
15 def add_pair(x: (Int, Int))(y: (Int, Int)) = |
|
16 (x._1 + y._1, x._2 + y._2) |
|
17 |
|
18 def is_legal(n: Int)(x: (Int, Int)) = |
|
19 0 <= x._1 && 0 <= x._2 && x._1 < n && x._2 < n |
|
20 |
|
21 def moves(n: Int)(x: (Int, Int)): List[(Int, Int)] = { |
|
22 List((1, 2),(2, 1),(2, -1),(1, -2), |
|
23 (-1, -2),(-2, -1),(-2, 1),(-1, 2)).map(add_pair(x)).filter(is_legal(n)) |
|
24 } |
|
25 |
|
26 def ordered_moves(n: Int)(steps: List[(Int, Int)])(x : (Int, Int)): List[(Int, Int)] = |
|
27 moves(n)(x).sortBy((x: (Int, Int)) => moves(n)(x).filterNot(steps.contains(_)).length) |
|
28 |
|
29 moves(8)(1,3) |
|
30 ordered_moves(8)(Nil)(1,3) |
|
31 ordered_moves(8)(List((2, 4), (2, 6)))(1,3) |
|
32 |
|
33 // non-circle tour parallel |
|
34 def tour(n: Int)(steps: List[(Int, Int)]): Unit = { |
|
35 if (steps.length == n * n) |
|
36 print_board(n)(steps) |
|
37 else |
|
38 for (x <- moves(n)(steps.head); if (!steps.contains(x))) tour(n)(x :: steps) |
|
39 } |
|
40 |
|
41 // non-circle tour |
|
42 def ctour(n: Int)(steps: List[(Int, Int)]): Unit = { |
|
43 if (steps.length == n * n && moves(n)(steps.head).contains(steps.last)) |
|
44 print_board(n)(steps) |
|
45 else |
|
46 for (x <- moves(n)(steps.head); if (!steps.contains(x))) ctour(n)(x :: steps) |
|
47 } |
|
48 |
|
49 |
|
50 def faster_tour(n: Int)(steps: List[(Int, Int)]): Unit = { |
|
51 if (steps.length == n * n && moves(n)(steps.head).contains(steps.last)) |
|
52 print_board(n)(steps) |
|
53 else |
|
54 for (x <- ordered_moves(n)(steps)(steps.head); if (!steps.contains(x))) faster_tour(n)(x :: steps) |
|
55 } |
|
56 |
|
57 |
|
58 val n1 = 5 |
|
59 println(s"simple tour: n = $n1") |
|
60 |
|
61 Try { |
|
62 for (i <- 0 until n1; j <- 0 until n1) { |
|
63 tour(n1)(List((i, j))) |
|
64 } |
|
65 } |
|
66 |
|
67 |
|
68 val n2 = 6 |
|
69 println(s"circle tour: n = $n2") |
|
70 |
|
71 Try { |
|
72 for (i <- 0 until n2; j <- 0 until n2) { |
|
73 ctour(n2)(List((i, j))) |
|
74 } |
|
75 } |
|
76 |
|
77 |
|
78 val n3 = 8 |
|
79 println(s"fast circle tour: n = $n3") |
|
80 |
|
81 Try { |
|
82 for (i <- 0 until n3; j <- 0 until n3) { |
|
83 faster_tour(n3)(List((i, j))) |
|
84 } |
|
85 } |
|
86 |
|
87 println("finished") |