--- a/main_solution4/knight4.scala Thu Nov 03 09:55:11 2022 +0000
+++ b/main_solution4/knight4.scala Thu Nov 03 11:30:09 2022 +0000
@@ -1,14 +1,7 @@
// Part 4 about finding a single tour on "mutilated" chessboards
//==============================================================
-object M4d {
-
-// !!! Copy any function you need from file knight1.scala !!!
-// !!! or knight2.scala or knight3.scala !!!
-//
-// If you need any auxiliary function, feel free to
-// implement it, but do not make any changes to the
-// templates below.
+object M4d { // for preparing the jar
type Pos = (Int, Int)
type Path = List[Pos]
@@ -23,11 +16,38 @@
}
}
-// ADD YOUR CODE BELOW
-//======================
+def add_pair(x: Pos, y: Pos): Pos =
+ (x._1 + y._1, x._2 + y._2)
+
+def is_legal(dim: Int, path: Path, x: Pos): Boolean =
+ 0 <= x._1 && 0 <= x._2 && x._1 < dim && x._2 < dim && !path.contains(x)
+
+def moves(x: Pos): List[Pos] =
+ List(( 1, 2),( 2, 1),( 2, -1),( 1, -2),
+ (-1, -2),(-2, -1),(-2, 1),(-1, 2)).map(add_pair(x, _))
+
+def legal_moves(dim: Int, path: Path, x: Pos): List[Pos] =
+ moves(x).filter(is_legal(dim, path, _))
+
+import scala.annotation.tailrec
-// (10)
-def one_tour_pred(dim: Int, path: Path, n: Int, pred: Pos => Boolean): Option[Path] = ???
+@tailrec
+def first(xs: List[Pos], f: Pos => Option[Path]): Option[Path] = xs match {
+ case Nil => None
+ case x::xs => {
+ val result = f(x)
+ if (result.isDefined) result else first(xs, f)
+ }
+}
+
+
+def one_tour_pred(dim: Int, path: Path, n: Int, pred: Pos => Boolean): Option[Path] = {
+ if (path.length == n) Some(path)
+ else
+ first(legal_moves(dim, path, path.head).filter(pred), (x: Pos) => one_tour_pred(dim, x::path, n, pred))
+}
+
+//print_board(8, one_tour_pred(8, List((0, 0)), 40, x => x._1 < 5).get)
}