progs/lecture4.scala
changeset 383 c02929f2647c
parent 382 1bd800376e0c
child 384 6e1237691307
--- a/progs/lecture4.scala	Wed Dec 02 01:15:14 2020 +0000
+++ b/progs/lecture4.scala	Mon Dec 07 01:25:41 2020 +0000
@@ -271,40 +271,47 @@
               |1..5...92
               |..7.9.41.""".stripMargin.replaceAll("\\n", "")
 
-candidates(game0, (0, 0))
+
 
 type Pos = (Int, Int)
 val EmptyValue = '.'
 val MaxValue = 9
 
+def pretty(game: String): String = 
+  "\n" + (game.grouped(MaxValue).mkString("\n"))
+
+pretty(game0)
+
+
 val allValues = "123456789".toList
 val indexes = (0 to 8).toList
 
-
 def empty(game: String) = game.indexOf(EmptyValue)
 def isDone(game: String) = empty(game) == -1 
-def emptyPosition(game: String) = 
-  (empty(game) % MaxValue, empty(game) / MaxValue)
-
+def emptyPosition(game: String) = {
+  val e = empty(game)
+  (e % MaxValue, e / MaxValue)
+}
 
 def get_row(game: String, y: Int) = 
   indexes.map(col => game(y * MaxValue + col))
 def get_col(game: String, x: Int) = 
   indexes.map(row => game(x + row * MaxValue))
 
-get_row(game0, 0)
+//get_row(game0, 0)
+//get_row(game0, 1)
+//get_col(game0, 0)
 
 def get_box(game: String, pos: Pos): List[Char] = {
     def base(p: Int): Int = (p / 3) * 3
     val x0 = base(pos._1)
     val y0 = base(pos._2)
     val ys = (y0 until y0 + 3).toList
-    (x0 until x0 + 3).toList.flatMap(x => ys.map(y => game(x + y * MaxValue)))
+    (x0 until x0 + 3).toList
+      .flatMap(x => ys.map(y => game(x + y * MaxValue)))
 }
 
-//get_row(game0, 0)
-//get_row(game0, 1)
-//get_col(game0, 0)
+
 //get_box(game0, (3, 1))
 
 
@@ -313,26 +320,25 @@
   game.updated(pos, value)
 
 def toAvoid(game: String, pos: Pos): List[Char] = 
-  (get_col(game, pos._1) ++ get_row(game, pos._2) ++ get_box(game, pos))
+  (get_col(game, pos._1) ++ 
+   get_row(game, pos._2) ++ 
+   get_box(game, pos))
 
 def candidates(game: String, pos: Pos): List[Char] = 
   allValues.diff(toAvoid(game, pos))
 
 //candidates(game0, (0,0))
 
-def pretty(game: String): String = 
-  "\n" + (game.sliding(MaxValue, MaxValue).mkString("\n"))
 
 def search(game: String): List[String] = {
   if (isDone(game)) List(game)
   else {
     val cs = candidates(game, emptyPosition(game))
-    cs.map(c => search(update(game, empty(game), c))).toList.flatten
+    cs.map(c => search(update(game, empty(game), c))).flatten
   }
 }
 
-List(List("sol1"), List("sol2", "sol3")).flatten
-
+pretty(game0)
 search(game0).map(pretty)
 
 val game1 = """23.915...