Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>After Andreas comment I changed the <code>m: Array[Array[Char]]</code> into <code>m: List[List[Char]]</code> which prevents any unnecessary and unwanted changes to it. The final looping method is </p> <pre><code> def reduc(f: (Int, Int) =&gt; Int, accu: Int, l: Int, u: Int, m1: List[List[Char]]):Int = accu + (l until u).toArray.par.reduce(f(accu, _) + f(accu, _)) </code></pre> <p>and I had to pass m as an argument to each used function, so every one of them had its own instance of it. The whole code:</p> <pre><code> object SudokuSolver extends App{ // The board is represented by an Array of strings (Arrays of Chars), val source = scala.io.Source.fromFile("./puzzle") val lines = source.getLines.toList val m: List[List[Char]] = for ( str &lt;- lines; line: List[Char] = str.toList ) yield line source.close() // For prInting m def printSud(m: List[List[Char]]) = { Console.println("") m map (println) } Console.println("\nINPUT:") printSud(m) def invalid(i:Int, x:Int, y:Int, n:Char,m1: List[List[Char]]): Boolean = i &lt; 9 &amp;&amp; (m1(y)(i) == n || m1(i)(x) == n || m1(y / 3 * 3 + i / 3)(x / 3 * 3 + i % 3) == n || invalid(i + 1, x, y, n, m1)) def reduc(f: (Int, Int) =&gt; Int, accu: Int, l: Int, u: Int, m1: List[List[Char]]): Int = accu + (l until u).toArray.par.reduce(f(accu, _) + f(accu, _)) def search(x: Int, y: Int, accu: Int, m1: List[List[Char]]): Int = Pair(x, y) match { case Pair(9, y) =&gt; search(0, y + 1, accu, m1) // next row case Pair(0, 9) =&gt; { printSud(m1); accu + 1 } // found a solution case Pair(x, y) =&gt; if (m1(y)(x) != '0') search(x + 1, y, accu, m1) // place is filled, we skip it. else // box is not filled, we try all n in {1,...,9} reduc((accu: Int, n: Int) =&gt; { if (invalid(0, x, y, (n + 48).asInstanceOf[Char], m1)) accu else { // n fits here val line = List(m1(y).patch(x, Seq((n + 48).asInstanceOf[Char]), 1)) val m2 = m1.patch(y, line, 1) val newaccu = search(x + 1, y, accu, m2); val m3 = m1.patch(y, m1(y).patch(x, Seq(0), 1), 1) newaccu } }, accu, 1, 10, m1) } Console.println("\n" + search(0, 0, 0, m) + " solution(s)") } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload