Created
April 23, 2019 15:58
-
-
Save karimEssawi/340eafb433c597bf1ef4e4d14827d422 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Sudoku { | |
def main(args: Array[String]): Unit = { | |
val solvedBoard = Seq( | |
9,6,1,5,7,8,4,3,2, | |
2,7,3,4,1,9,8,6,5, | |
8,5,4,6,2,3,1,7,9, | |
3,8,2,7,6,5,9,1,4, | |
4,1,7,9,3,2,6,5,8, | |
5,9,6,1,8,4,7,2,3, | |
7,2,5,8,9,6,3,4,1, | |
1,4,8,3,5,7,2,9,6, | |
6,3,9,2,4,1,5,8,7 | |
) | |
val unsolvedBoard = Seq( | |
1,1,1,4,4,4,7,7,7, | |
1,1,1,4,4,4,7,7,7, | |
1,1,1,4,4,4,7,7,7, | |
2,2,2,5,5,5,8,8,8, | |
2,2,2,5,5,5,8,8,8, | |
2,2,2,5,5,5,8,8,8, | |
3,3,3,6,6,6,9,9,9, | |
3,3,3,6,6,6,9,9,9, | |
3,3,3,6,6,6,9,9,9 | |
) | |
println(isSolved(solvedBoard)) | |
println(isSolved(unsolvedBoard)) | |
} | |
def isSolved(values: Seq[Int]): Boolean = { | |
require(values.size == 81, "Board must contain 81 cells") | |
def solvedVec(v: Vector[Int]) = v.distinct.sorted == Vector.range(1, 10) | |
def squareIndices(sr:Int, sc:Int) = for { | |
i <- 0 until 3 | |
j <- 0 until 3 | |
} yield (sr*3+i,sc*3+j) | |
val board = values.toVector.grouped(9).toVector | |
def square(sr: Int, sc: Int) = squareIndices(sr, sc).toVector.map { case(r, c) => board(r)(c) } | |
val pairs = for { | |
r <- 0 until 3 | |
c <- 0 until 3 | |
} yield (r, c) | |
val rowsSolved = board.forall(solvedVec) | |
val columnsSolved = board.transpose.forall(solvedVec) | |
val squaresSolved = pairs.forall { case(r, c) => solvedVec(square(r, c)) } | |
rowsSolved && columnsSolved && squaresSolved | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment