Write a program that will accept a 2D array and check if it contains a 100% correct Sudoku solution. For those unfamiliar with the rules, check out http://www.sudoku.name/rules/ .
Моё решение на Scala:
package solver object SudokuSolver { type Sudoku = IndexedSeq[IndexedSeq[Int]] def toSudoku( s: String): Sudoku = s.split("\n").toVector.map(_.split(" ").map(_.toInt).toVector) def check( sudoku: Sudoku )= linesCorrect(sudoku) && rowsCorrect(sudoku) && blocksCorrect(sudoku) private def isCorrect( splitMethod: Sudoku=>Sudoku) ={ s:Sudoku => splitMethod(s).filter( isCombinationWrong).isEmpty } private val blocksCorrect = isCorrect(splitToBlocks) private val rowsCorrect = isCorrect(splitToRows) private val linesCorrect = isCorrect(splitToLines) private def splitToLines( sudoku: Sudoku) = sudoku private def splitToRows( sudoku: Sudoku) = for( i <- 0 to 8 ) yield( for(j<-0 to 8) yield( sudoku(j)(i) ) ) private def splitToBlocks( sudoku: Sudoku) = for( i <- 0 to 8 by 3; j <- 0 to 8 by 3 ) yield( for(ii <- 0 to 2; jj<- 0 to 2 ) yield(sudoku(i+ii)(j+jj)) ) private def isCombinationWrong( comb: IndexedSeq[Int]) = comb.min != 1 || comb.max != 9 || comb.toSet.size != 9 }
Комментариев нет:
Отправить комментарий