[Solved] Sudoku Solution Checker in R [closed]


Here is one. It uses the interesting property found here: https://math.stackexchange.com/a/157716

check.solutions <- function(solutions) {
   board <- matrix(1:81, 9, 9)
   row.idx <- row(board)
   col.idx <- col(board)
   squ.idx <- (row.idx - 1L) %/% 3L  + 1L + 3L * (col.idx - 1L) %/% 3L
   grp.mat <- t(cbind(sapply(1:9, `==`, row.idx),
                      sapply(1:9, `==`, col.idx),
                      sapply(1:9, `==`, squ.idx)))
   flat.sol <- 2^(solutions - 1)
   dim(flat.sol) <- c(81, dim(flat.sol)[3])
   colSums(grp.mat %*% flat.sol == 511) == 27
}

Quick check that it works. Here is a good solution:

s1 <- matrix(c(9,4,6,1,7,3,8,2,5,
               2,8,3,9,4,5,1,7,6,
               5,7,1,8,2,6,9,4,3,
               4,1,5,2,3,7,6,9,8,
               8,3,9,4,6,1,7,5,2,
               6,2,7,5,9,8,4,3,1,
               3,6,4,7,1,2,5,8,9,
               7,5,2,6,8,9,3,1,4,
               1,9,8,3,5,4,2,6,7), 9, 9)

and a bad one:

s2 <- s1
s2[1:2] <- s2[2:1]

Then indeed:

check.solutions(array(c(s1, s2), c(9,9,2)))
# [1]  TRUE FALSE

solved Sudoku Solution Checker in R [closed]