knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

Travis build status

sudokuplyr

The goal of sudokuplyr is to provide simple functions for solving, creating, and analyzing sudoku puzzles in R.

Installation

You can install sudokuplyr from github with:

# install.packages("devtools")
devtools::install_github("alexpavlakis/sudokuplyr")

Usage

The following methods are available for objects of class sudoku:

as.sudoku will convert sudoku puzzles represented as matrices, vectors, or strings into objects of class sudoku.

# A sudoku in string format, with periods for unknown cells
raw_sudoku <- "1.......2.9.4...5...6...7...5.9.3.......7.......85..4.7.....6...3...9.8...2.....1"
s <- as.sudoku(raw_sudoku)

# Print
print(s)

# Solve
solve(s)

# Plot
plot(s)

# Summarize
summary(s)

solve_sudoku, print_sudoku, analyze_sudoku, and plot_sudoku operate on 9x9 matrices directly.

solve_sudoku completes puzzles in the blink of an eye. The example below shows the time taken to solve an easy puzzle (49 empty cells) and a hard puzzle (59 empty cells) that come with sudokuplyr. Both are solved in a fraction of a millisecond on a MacBook Air.

library(microbenchmark)

m <- microbenchmark(easy = solve(sudoku),
                    hard = solve(hard_sudoku), times = 100, unit = 'ms')
print(m, digits = 2)

generate_sudoku creates randomly generated complete sudoku puzzles. The seed argument can be used to create reproducible random puzzles or left NULL (default). generate_puzzle creates randomly generated incomplete sudoku puzzles with a specified number of clues.

new_puzzle <- generate_puzzle(clues = 32, unique = TRUE, seed = 56)
print(new_puzzle)

get_all_solutions generates all possible solutions for a given puzzle. Puzzles with fewer than 20-25 clues (depending on the puzzle, of course), can have a lot of solutions, and this function can take a while to find them all. Beware. Most puzzles that appear in newspapers and magazines have only one solution.

# This puzzle has a lot of solutions
puzzle <- generate_puzzle(clues = 28, unique = FALSE, seed = 56)
all_solutions <- get_all_solutions(puzzle, stop_early = FALSE)
length(all_solutions)

`



alexpavlakis/sudoku documentation built on Feb. 1, 2020, 6:49 p.m.