# R and Sudoku solvers: Plus ca change…

February 25, 2010
By

(This article was first published on Thinking inside the box , and kindly contributed to R-bloggers)

Christian Robert blogged about a particularly heavy-handed solution to last Sunday's Sudoku puzzle in Le Monde. That had my symapthy as I like evolutionary computing methods, and his chart is rather pretty. From there, this spread on to the REvolutions blogs where David Smith riffed on it, and showed the acual puzzle. That didn't stop things as Christian blogged once more about it, this time welcoming his post-doc Robin Ryder who posts a heavy analysis on all this that is a little much for me at this time of day.

But what everybody seems to be forgetting is that R has had a Sudoku solver for years, thanks to the sudoku package by David Brahm and Greg Snow which was first posted four years ago. What comes around, goes around.

With that, and about one minute of Emacs editing to get the Le Monde puzzle into the required ascii-art form, all we need to do is this:

R> library(sudoku)
R> s <- readSudoku("/tmp/sudoku.txt")
R> s
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    8    0    0    0    0    1    2    0    0
[2,]    0    7    5    0    0    0    0    0    0
[3,]    0    0    0    0    5    0    0    6    4
[4,]    0    0    7    0    0    0    0    0    6
[5,]    9    0    0    7    0    0    0    0    0
[6,]    5    2    0    0    0    9    0    4    7
[7,]    2    3    1    0    0    0    0    0    0
[8,]    0    0    6    0    2    0    1    0    9
[9,]    0    0    0    0    0    0    0    0    0
R> system.time(solveSudoku(s))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    8    4    9    6    7    1    2    5    3
[2,]    6    7    5    2    4    3    9    1    8
[3,]    3    1    2    9    5    8    7    6    4
[4,]    1    8    7    4    3    2    5    9    6
[5,]    9    6    4    7    8    5    3    2    1
[6,]    5    2    3    1    6    9    8    4    7
[7,]    2    3    1    8    9    4    6    7    5
[8,]    4    5    6    3    2    7    1    8    9
[9,]    7    9    8    5    1    6    4    3    2
user  system elapsed
5.288   0.004   5.951
R>

That took all of five seconds while my computer was also compiling a particularly resource-hungry C++ package....

Just in case we needed another illustration that it is hard to navigate the riches and wonders that is CRAN...

To leave a comment for the author, please follow the link and comment on his blog: Thinking inside the box .

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...