|
1 import scala.util._ |
|
2 |
|
3 class Computation[A,B](value: A, function: A => B) { |
|
4 lazy val result = function(value) |
|
5 } |
|
6 |
|
7 |
|
8 def print_board(n: Int)(steps: List[(Int, Int)]): Unit = { |
|
9 println |
|
10 for (i <- 0 until n) { |
|
11 for (j <- 0 until n) { |
|
12 print(f"${steps.indexOf((i, j))}%3.0f ") |
|
13 } |
|
14 println |
|
15 } |
|
16 } |
|
17 |
|
18 def add_pair(x: (Int, Int))(y: (Int, Int)) = |
|
19 (x._1 + y._1, x._2 + y._2) |
|
20 |
|
21 def is_legal(n: Int)(x: (Int, Int)) = |
|
22 0 <= x._1 && 0 <= x._2 && x._1 < n && x._2 < n |
|
23 |
|
24 def moves(n: Int)(steps: List[(Int, Int)])(x: (Int, Int)): List[(Int, Int)] = { |
|
25 List((1, 2),(2, 1),(2, -1),(1, -2), |
|
26 (-1, -2),(-2, -1),(-2, 1),(-1, 2)).map(add_pair(x)).filter(is_legal(n)).filterNot(steps.contains(_)) |
|
27 } |
|
28 |
|
29 def ordered_moves(n: Int)(steps: List[(Int, Int)])(x : (Int, Int)): List[(Int, Int)] = |
|
30 moves(n)(steps)(x).sortBy(moves(n)(steps)(_).length) |
|
31 |
|
32 moves(8)(Nil)(1,3) |
|
33 ordered_moves(8)(Nil)(1,3) |
|
34 ordered_moves(8)(List((2, 4), (2, 6)))(1,3) |
|
35 |
|
36 def first[A, B](xs: List[A], f: A => Set[B]): Set[B] = xs match { |
|
37 case Nil => Set() |
|
38 case x::xs => { |
|
39 val result = f(x) |
|
40 if (result == Set()) first(xs, f) else result |
|
41 } |
|
42 } |
|
43 |
|
44 // non-circular tour |
|
45 def tour(n: Int)(steps: List[(Int, Int)]): Option[List[(Int, Int)]] = { |
|
46 if (steps.length == n * n) Some(steps) |
|
47 else |
|
48 { val list = moves(n)(steps)(steps.head) map (x => new Computation(x, ((x:(Int, Int)) => tour(n)(x::steps)))) |
|
49 val found = list.par find (_.result.isDefined) |
|
50 found map (_.result.get) |
|
51 } |
|
52 } |
|
53 |
|
54 val n = 6 |
|
55 println(s"simple tour: n = $n") |
|
56 |
|
57 val starts = for (i <- (0 until n).toList; |
|
58 j <- (0 until n).toList) yield new Computation ((i, j), ((x:(Int, Int)) => tour(n)(x::Nil))) |
|
59 |
|
60 val found = starts.par find (_.result.isDefined) |
|
61 print_board(n)((found map (_.result.get)).get) |
|
62 |
|
63 //for measuring time |
|
64 def time_needed[T](i: Int, code: => T) = { |
|
65 val start = System.nanoTime() |
|
66 for (j <- 1 to i) code |
|
67 val end = System.nanoTime() |
|
68 (end - start)/(i * 1.0e9) |
|
69 } |
|
70 |
|
71 //for (i <- 1 to 20) { |
|
72 // println(i + ": " + "%.5f".format(time_needed(2, matches(EVIL1(i), "a" * i)))) |
|
73 //} |
|
74 |
|
75 |
|
76 |