testing3/knight1.scala
changeset 247 50a3b874008a
parent 222 e52cc402caee
child 284 9a04eb6a2291
equal deleted inserted replaced
246:178438912e5f 247:50a3b874008a
     1 // Part 1 about finding Knight's tours
     1 // Part 1 about finding and counting Knight's tours
     2 //=====================================
     2 //==================================================
     3 
     3 
     4 // If you need any auxiliary function, feel free to 
     4 //object CW8a {   // for preparing the jar
     5 // implement it, but do not make any changes to the
       
     6 // templates below. Also have a look whether the functions
       
     7 // at the end are of any help.
       
     8 
       
     9 
       
    10 
     5 
    11 type Pos = (Int, Int)    // a position on a chessboard 
     6 type Pos = (Int, Int)    // a position on a chessboard 
    12 type Path = List[Pos]    // a path...a list of positions
     7 type Path = List[Pos]    // a path...a list of positions
    13 
     8 
    14 //(1) Complete the function that tests whether the position x
       
    15 //    is inside the board and not yet element in the path.
       
    16 
     9 
    17 def is_legal(dim: Int, path: Path, x: Pos) : Boolean = {
    10 // for measuring time in the JAR
    18  if ((x._1 < dim && x._2 < dim) && !(path.contains(x)))
       
    19   true 
       
    20     else 
       
    21   false
       
    22 }
       
    23 
       
    24 
       
    25 
       
    26 //(2) Complete the function that calculates for a position x
       
    27 //    all legal onward moves that are not already in the path. 
       
    28 //    The moves should be ordered in a "clockwise" manner.
       
    29  
       
    30 
       
    31 def legal_moves(dim: Int, path: Path, x: Pos) : List[Pos] = {
       
    32   val legalMovesList = List((x._1 + 1, x._2 + 2), (x._1 + 2, x._2 + 1), (x._1 + 2, x._2 - 1), (x._1 + 1, x._2 - 2), (x._1 - 1, x._2 - 2), (x._1 - 2, x._2 - 1), (x._1 - 2, x._2 + 1), (x._1 - 1, x._2 + 2))
       
    33 
       
    34   for (i <- legalMovesList
       
    35     if (is_legal(dim, path, i)))
       
    36       yield i
       
    37 
       
    38 }
       
    39 
       
    40 
       
    41 //some test cases
       
    42 //
       
    43 //assert(legal_moves(8, Nil, (2,2)) == 
       
    44 //  List((3,4), (4,3), (4,1), (3,0), (1,0), (0,1), (0,3), (1,4)))
       
    45 //assert(legal_moves(8, Nil, (7,7)) == List((6,5), (5,6)))
       
    46 //assert(legal_moves(8, List((4,1), (1,0)), (2,2)) == 
       
    47 //  List((3,4), (4,3), (3,0), (0,1), (0,3), (1,4)))
       
    48 //assert(legal_moves(8, List((6,6)), (7,7)) == List((6,5), (5,6)))
       
    49 
       
    50 
       
    51 //(3) Complete the two recursive functions below. 
       
    52 //    They exhaustively search for knight's tours starting from the 
       
    53 //    given path. The first function counts all possible tours, 
       
    54 //    and the second collects all tours in a list of paths.
       
    55 
       
    56 def count_tours(dim: Int, path: Path) : Int = {
       
    57   if (path.size == (dim ^ 2)){
       
    58     List(path).size
       
    59   }  else {
       
    60     val totalTours = legal_moves(dim, path, path.head) 
       
    61     totalTours.map(element => count_tours(dim, element :: path)).sum
       
    62   } 
       
    63 }
       
    64 
       
    65 def enum_tours(dim: Int, path: Path) : List[Path] = {
       
    66   if (path.size == (dim ^ 2)){
       
    67     List(path)
       
    68   } else {
       
    69     val totalEnums = legal_moves(dim, path, path.head)
       
    70     totalEnums.map(element => enum_tours(dim, element :: path)).flatten
       
    71   }
       
    72 }
       
    73 
       
    74 
       
    75 //(5) Implement a first-function that finds the first 
       
    76 //    element, say x, in the list xs where f is not None. 
       
    77 //    In that case Return f(x), otherwise None. If possible,
       
    78 //    calculate f(x) only once.
       
    79 
       
    80 def first(xs: List[Pos], f: Pos => Option[Path]) : Option[Path] = {
       
    81   if (xs eq Nil) {
       
    82     None
       
    83   } else {
       
    84     if (f(xs.head) != None) {
       
    85       f(xs.head)
       
    86     } else {
       
    87       first(xs.tail, f)
       
    88     }
       
    89   }
       
    90 
       
    91 }
       
    92 
       
    93 
       
    94 // test cases
       
    95 //def foo(x: (Int, Int)) = if (x._1 > 3) Some(List(x)) else None
       
    96 //
       
    97 //first(List((1, 0),(2, 0),(3, 0),(4, 0)), foo)   // Some(List((4,0)))
       
    98 //first(List((1, 0),(2, 0),(3, 0)), foo)          // None
       
    99 
       
   100 
       
   101 
       
   102 
       
   103 //(6) Implement a function that uses the first-function from (5) for
       
   104 //    trying out onward moves, and searches recursively for a
       
   105 //    knight tour on a dim * dim-board.
       
   106 
       
   107 
       
   108 //def first_tour(dim: Int, path: Path) : Option[Path] = ...
       
   109  
       
   110 
       
   111 
       
   112 
       
   113 
       
   114 
       
   115 /* Helper functions
       
   116 
       
   117 
       
   118 // for measuring time
       
   119 def time_needed[T](code: => T) : T = {
    11 def time_needed[T](code: => T) : T = {
   120   val start = System.nanoTime()
    12   val start = System.nanoTime()
   121   val result = code
    13   val result = code
   122   val end = System.nanoTime()
    14   val end = System.nanoTime()
   123   println(f"Time needed: ${(end - start) / 1.0e9}%3.3f secs.")
    15   println(f"Time needed: ${(end - start) / 1.0e9}%3.3f secs.")
   124   result
    16   result
   125 }
    17 }
   126 
       
   127 // can be called for example with
       
   128 //     time_needed(count_tours(dim, List((0, 0))))
       
   129 // in order to print out the time that is needed for 
       
   130 // running count_tours
       
   131 
    18 
   132 // for printing a board
    19 // for printing a board
   133 def print_board(dim: Int, path: Path): Unit = {
    20 def print_board(dim: Int, path: Path): Unit = {
   134   println
    21   println
   135   for (i <- 0 until dim) {
    22   for (i <- 0 until dim) {
   138     }
    25     }
   139     println
    26     println
   140   } 
    27   } 
   141 }
    28 }
   142 
    29 
       
    30 def is_legal(dim: Int, path: Path, x: Pos): Boolean = 
       
    31   0 <= x._1 && 0 <= x._2 && x._1 < dim && x._2 < dim && !path.contains(x)
   143 
    32 
       
    33 // testcases
       
    34 //assert(is_legal(8, Nil, (3, 4)) == true)
       
    35 //assert(is_legal(8, List((4, 1), (1, 0)), (4, 1)) == false)
       
    36 //assert(is_legal(2, Nil, (0, 0)) == true)
       
    37 
       
    38 
       
    39 def add_pair(x: Pos, y: Pos): Pos = 
       
    40   (x._1 + y._1, x._2 + y._2)
       
    41 
       
    42 def moves(x: Pos): List[Pos] = 
       
    43   List(( 1,  2),( 2,  1),( 2, -1),( 1, -2),
       
    44        (-1, -2),(-2, -1),(-2,  1),(-1,  2)).map(add_pair(x, _))
       
    45 
       
    46 // 1 mark
       
    47 
       
    48 def legal_moves(dim: Int, path: Path, x: Pos): List[Pos] = 
       
    49   moves(x).filter(is_legal(dim, path, _))
       
    50 
       
    51 // testcases
       
    52 //assert(legal_moves(8, Nil, (2,2)) == 
       
    53 //  List((3,4), (4,3), (4,1), (3,0), (1,0), (0,1), (0,3), (1,4)))
       
    54 //assert(legal_moves(8, Nil, (7,7)) == List((6,5), (5,6)))
       
    55 //assert(legal_moves(8, List((4,1), (1,0)), (2,2)) == 
       
    56 //  List((3,4), (4,3), (3,0), (0,1), (0,3), (1,4)))
       
    57 //assert(legal_moves(8, List((6,6)), (7,7)) == List((6,5), (5,6)))
       
    58 //assert(legal_moves(1, Nil, (0,0)) == List())
       
    59 //assert(legal_moves(2, Nil, (0,0)) == List())
       
    60 //assert(legal_moves(3, Nil, (0,0)) == List((1,2), (2,1)))
       
    61 
       
    62 // 2 marks
       
    63 
       
    64 def tcount_tours(dim: Int, path: Path): Int = {
       
    65   if (path.length == dim * dim) 1
       
    66   else 
       
    67     (for (x <- legal_moves(dim, path, path.head)) yield tcount_tours(dim, x::path)).sum
       
    68 }
       
    69 
       
    70 def count_tours(dim: Int, path: Path) =
       
    71   time_needed(tcount_tours(dim: Int, path: Path))
       
    72 
       
    73 
       
    74 def tenum_tours(dim: Int, path: Path): List[Path] = {
       
    75   if (path.length == dim * dim) List(path)
       
    76   else 
       
    77     (for (x <- legal_moves(dim, path, path.head)) yield tenum_tours(dim, x::path)).flatten
       
    78 }
       
    79 
       
    80 def enum_tours(dim: Int, path: Path) =
       
    81   time_needed(tenum_tours(dim: Int, path: Path))
       
    82 
       
    83 // test cases
       
    84 
       
    85 /*
       
    86 def count_all_tours(dim: Int) = {
       
    87   for (i <- (0 until dim).toList; 
       
    88        j <- (0 until dim).toList) yield count_tours(dim, List((i, j)))
       
    89 }
       
    90 
       
    91 def enum_all_tours(dim: Int): List[Path] = {
       
    92   (for (i <- (0 until dim).toList; 
       
    93         j <- (0 until dim).toList) yield enum_tours(dim, List((i, j)))).flatten
       
    94 }
       
    95 
       
    96 
       
    97 println("Number of tours starting from (0, 0)")
       
    98 
       
    99 for (dim <- 1 to 5) {
       
   100   println(s"${dim} x ${dim} " + time_needed(0, count_tours(dim, List((0, 0)))))
       
   101 }
       
   102 
       
   103 println("Number of tours starting from all fields")
       
   104 
       
   105 for (dim <- 1 to 5) {
       
   106   println(s"${dim} x ${dim} " + time_needed(0, count_all_tours(dim)))
       
   107 }
       
   108 
       
   109 for (dim <- 1 to 5) {
       
   110   val ts = enum_tours(dim, List((0, 0)))
       
   111   println(s"${dim} x ${dim} ")   
       
   112   if (ts != Nil) {
       
   113     print_board(dim, ts.head)
       
   114     println(ts.head)
       
   115   }
       
   116 }
   144 */
   117 */
       
   118 
       
   119 // 1 mark
       
   120 
       
   121 def first(xs: List[Pos], f: Pos => Option[Path]): Option[Path] = xs match {
       
   122   case Nil => None
       
   123   case x::xs => {
       
   124     val result = f(x)
       
   125     if (result.isDefined) result else first(xs, f)
       
   126   }
       
   127 }
       
   128 
       
   129 // test cases
       
   130 //def foo(x: (Int, Int)) = if (x._1 > 3) Some(List(x)) else None
       
   131 //
       
   132 //first(List((1, 0),(2, 0),(3, 0),(4, 0)), foo)
       
   133 //first(List((1, 0),(2, 0),(3, 0)), foo)
       
   134 
       
   135 
       
   136 // 1 mark
       
   137 
       
   138 def tfirst_tour(dim: Int, path: Path): Option[Path] = {
       
   139   if (path.length == dim * dim) Some(path)
       
   140   else
       
   141     first(legal_moves(dim, path, path.head), (x:Pos) => tfirst_tour(dim, x::path))
       
   142 }
       
   143 
       
   144 def first_tour(dim: Int, path: Path) = 
       
   145   time_needed(tfirst_tour(dim: Int, path: Path))
       
   146 
       
   147 
       
   148 /*
       
   149 for (dim <- 1 to 8) {
       
   150   val t = first_tour(dim, List((0, 0)))
       
   151   println(s"${dim} x ${dim} " + (if (t == None) "" else { print_board(dim, t.get) ; "" }))
       
   152 }
       
   153 */
       
   154 
       
   155 // 15 secs for 8 x 8
       
   156 //val ts1 = time_needed(0,first_tour(8, List((0, 0))).get)
       
   157 
       
   158 // no result for 4 x 4
       
   159 //val ts2 = time_needed(0, first_tour(4, List((0, 0))))
       
   160 
       
   161 // 0.3 secs for 6 x 6
       
   162 //val ts3 = time_needed(0, first_tour(6, List((0, 0))))
       
   163 
       
   164 // 15 secs for 8 x 8
       
   165 //time_needed(0, print_board(8, first_tour(8, List((0, 0))).get))
       
   166 
       
   167 
       
   168 //}
       
   169 
       
   170