SlideShare a Scribd company logo
SOLVING SUDOKU
Graham Hutton
University of Nottingham
(with thanks to Richard Bird)
2
What is Sudoku?
A simple but addictive puzzle, invented in the
USA in 1979 and called Number Place;
Became popular in Japan in 1986, where it was
renamed Sudoku (~ “single number”);
First appeared in UK newspapers in 2004, and
became an international craze in 2005.
3
Example
Fill in the grid so that every row, column and box
contains each of the numbers 1 to 9:
2 1 3 8
5
7 6
1 3
9 8 1 2 5 7
3 1 8
9 8 2
5 6 9 7 8 4
4 2 5
4
Example
Fill in the grid so that every row, column and box
contains each of the numbers 1 to 9:
2 1 3 8
5
7 6
1 3
9 8 1 2 5 7
3 1 8
9 8 2
5 6 9 7 8 4
4 2 5
What number
must go here?
5
Example
Fill in the grid so that every row, column and box
contains each of the numbers 1 to 9:
2 1 3 8
5
7 6
1 3
9 8 1 2 5 7
3 1 8
9 8 2
5 6 9 7 8 4
4 2 5
1, as 2 and 3
already appear
in this column.
1
6
Example
Fill in the grid so that every row, column and box
contains each of the numbers 1 to 9:
2 1 3 8
5
7 6
1 3
9 8 1 2 5 7
3 1 8
9 8 2
1 5 6 9 7 8 4
4 2 5
7
Example
Fill in the grid so that every row, column and box
contains each of the numbers 1 to 9:
2 1 3 8
5
7 6
1 3
9 8 1 2 5 7
3 1 8
9 8 2
1 5 6 9 7 8 4
4 2 5
3
8
Example
Fill in the grid so that every row, column and box
contains each of the numbers 1 to 9:
2 1 3 8
5
7 6
1 3
9 8 1 2 5 7
3 1 8
9 8 2
1 5 3 6 9 7 8 4
4 2 5
9
Example
Fill in the grid so that every row, column and box
contains each of the numbers 1 to 9:
2 1 3 8
5
7 6
1 3
9 8 1 2 5 7
3 1 8
9 8 2
1 5 3 6 9 7 8 4
4 2 5
2
10
Example
Fill in the grid so that every row, column and box
contains each of the numbers 1 to 9:
2 1 3 8
5
7 6
1 3
9 8 1 2 5 7
3 1 8
9 8 2
1 5 2 3 6 9 7 8 4
4 2 5
And so on…
11
Example
Fill in the grid so that every row, column and box
contains each of the numbers 1 to 9:
2 4 9 5 7 1 6 3 8
8 6 1 4 3 2 9 7 5
5 7 3 9 8 6 1 4 2
7 2 5 6 9 8 4 1 3
6 9 8 1 4 3 2 5 7
3 1 4 7 2 5 8 6 9
9 3 7 8 1 4 2 5 6
1 5 2 3 6 9 7 8 4
4 8 6 2 5 7 3 9 1
The unique
solution for this
easy puzzle.
12
This Talk
We show how to develop a program that can
solve any Sudoku puzzle in an instant;
Start with a simple but impractical program,
which is improved in a series of steps;
Emphasis on pictures rather than code, plus
some lessons about algorithm design.
13
Representing a Grid
type Grid = Matrix Char
type Matrix a = [Row a]
type Row a = [a]
A grid is essentially a list of lists, but
matrices and rows will be useful later on.
14
Examples
easy :: Grid
easy = [ "2 1 38" ,
" 5" ,
" 7 6 " ,
" 13 " ,
" 981 257" ,
"31 8 " ,
"9 8 2 " ,
" 5 69784" ,
"4 25 " ]
empty :: Grid
empty = replicate 9 (replicate 9 ' ')
15
Extracting Rows
rows :: Matrix a → [Row a]
rows m = m
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
16
… Columns
cols :: Matrix a → [Row a]
cols m = transpose m
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
17
… And Boxes
boxs :: Matrix a → [Row a]
boxs m = <omitted>
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
1 2 5 6
3 4 7 8
9 10 13 14
11 12 15 16
18
Validity Checking
Let us say that a grid is valid if it has no duplicate
entries in any row, column or box:
valid :: Grid → Bool
valid g = all nodups (rows g) ∧
all nodups (cols g) ∧
all nodups (boxs g)
A direct implementation,
without concern for efficiency.
19
Making Choices
Replace each blank square in a grid by all possible
numbers 1 to 9 for that square:
choices :: Grid → Matrix [Char]
1 2 3
4 5 6 3
7 8 9
1 2 3
4 4 5 6
7 8 9
3
4
20
Collapsing Choices
Transform a matrix of lists into a list of matrices by
considering all combinations of choices:
collapse :: Matrix [a] → [Matrix a]
1 3
4 1
2 3
4 2
2 3
4 1
1 3
4 2
1 2 3
4 1 2
21
A Brute Force Solver
solve :: Grid → [Grid]
solve = filter valid . collapse . choices
Consider all possible choices for
each blank square, collapse the
resulting matrix, then filter out the
valid grids.
22
Does It Work?
> solve easy
ERROR: out of memory
Simple, but
impractical!
The easy example has 51 blank squares, resulting
in 951
grids to consider, which is a huge number:
463839768658810197932815016789059145431896769800
9
23
Reducing The Search Space
Many choices that are considered will conflict
with entries provided in the initial grid;
For example, an initial entry of 1 precludes
another 1 in the same row, column or box;
Pruning such invalid choices before collapsing
will considerably reduce the search space.
24
Pruning
Remove all choices that occur as single entries in
the corresponding row, column or box:
prune :: Matrix [Char] → Matrix [Char]
1 1 2 4
1 3 3 4
1 2 4
3 3 4
25
And Again
Pruning may leave new single entries, so it makes
sense to iterate the pruning process:
1 2 4
3 3 4
26
And Again
Pruning may leave new single entries, so it makes
sense to iterate the pruning process:
1 2 4
3 4
27
And Again
Pruning may leave new single entries, so it makes
sense to iterate the pruning process:
1 2
3 4
28
And Again
Pruning may leave new single entries, so it makes
sense to iterate the pruning process:
1 2
3 4
We have now
reached a fixpoint of
the pruning function.
29
An Improved Solver
solve’ :: Grid → [Grid]
solve’ =
filter valid . collapse . fix prune . choices
For the easy example, the pruning process alone
is enough to completely solve the puzzle:
> solve’ easy
Terminate
s instantly!
30
But…
> solve' gentle
No solution after two
hours - we need to
think further!
For a gentle example, pruning leaves around 381
grids to consider, which is still a huge number:
44342648824303776994824963061914989280
3
31
Reducing The Search Space
After pruning there may still be many choices
that can never lead to a solution;
But such bad choices will be duplicated many
times during the collapsing process;
Discarding these bad choices is the key to
obtaining an efficient Sudoku solver.
32
Blocked Matrices
Let us say that a matrix is blocked if some square
has no choices left, or if some row, column, or
box has a duplicated single choice:
Key idea - a blocked
matrix can never
lead to a solution.
1 1 2 1
3 4 3
33
Expanding One Choice
Transform a matrix of lists into a list of matrices by
expanding the first square with choices:
expand :: Matrix [a] → [Matrix [a]]
1 2 3
4 1 2
2 3
4 1 2
1 3
4 1 2
34
Our Final Solver
solve’’ :: Grid → [Grid]
solve’’ = search . prune . choices
search :: Matrix [Char] → [Grid]
search m
| blocked m = []
| complete m = collapse m
| otherwise = [g | m' ← expand m
, g ← search (prune m')]
35
Notes
Using fix prune rather than prune makes the
program run slower in this case;
No need to filter out valid grids, because they
are guaranteed to be valid by construction;
This program can now solve any newspaper
Sudoku puzzle in an instant!
36
The Result
This program has
saved my life -
my Sudoku
addiction is finally
cured!!
Subliminal Message
Haskell is the world's greatest
programming language.

More Related Content

What's hot

Diabolic Str8ts #3 and Weekly Extreme #63 - Solution
Diabolic Str8ts #3 and Weekly Extreme #63 - SolutionDiabolic Str8ts #3 and Weekly Extreme #63 - Solution
Diabolic Str8ts #3 and Weekly Extreme #63 - Solution
SlowThinker
 
Series & Progression Mathematics
Series & Progression MathematicsSeries & Progression Mathematics
Series & Progression Mathematics
Pratima Nayak ,Kendriya Vidyalaya Sangathan
 
Expanding
ExpandingExpanding
Expanding
mathsteacher101
 
Inequalities day 1 worked
Inequalities day 1 workedInequalities day 1 worked
Inequalities day 1 worked
Jonna Ramsey
 
Unit 5.4
Unit 5.4Unit 5.4
Unit 5.4
Jessica Scott
 
Year 11 foundation pythagoras 1
Year 11 foundation pythagoras 1Year 11 foundation pythagoras 1
Year 11 foundation pythagoras 1
terryrobbo
 
4.9 Graphing Quadratic Inequalities
4.9 Graphing Quadratic Inequalities4.9 Graphing Quadratic Inequalities
4.9 Graphing Quadratic Inequalities
swartzje
 
Level 4 a1
Level 4 a1Level 4 a1
Level 4 a1
h-butler
 
Math is Awesome ACT Prep
Math is Awesome ACT PrepMath is Awesome ACT Prep
Math is Awesome ACT Prep
JTKnull
 
Numbers session 1 class 2
Numbers session 1 class 2Numbers session 1 class 2
Numbers session 1 class 2
George Prep
 
Polynomials intro
Polynomials introPolynomials intro
Polynomials intro
Shaun Wilson
 
Diabolic Str8ts #2
Diabolic Str8ts #2Diabolic Str8ts #2
Diabolic Str8ts #2
SlowThinker
 
Sequence: Generating a Formula
Sequence: Generating a FormulaSequence: Generating a Formula
Sequence: Generating a Formula
Solomon Hippocrates S. Flores
 
Algebra 7 Point 6
Algebra 7 Point 6Algebra 7 Point 6
Algebra 7 Point 6
herbison
 
5.7 Quadratic Inequalities
5.7 Quadratic Inequalities5.7 Quadratic Inequalities
5.7 Quadratic Inequalities
hisema01
 
Mathnasium Presentation (1)
Mathnasium Presentation (1)Mathnasium Presentation (1)
Mathnasium Presentation (1)
Muhammad Arslan
 
Group activity
Group activityGroup activity
Group activity
marleyb93
 
Str8ts Weekly Extreme #53 - Solution
Str8ts Weekly Extreme #53 - SolutionStr8ts Weekly Extreme #53 - Solution
Str8ts Weekly Extreme #53 - Solution
SlowThinker
 
Nikhil number pattern formulas
Nikhil number pattern formulasNikhil number pattern formulas
Nikhil number pattern formulas
ecooperms
 
Applied 20S January 7, 2009
Applied 20S January 7, 2009Applied 20S January 7, 2009
Applied 20S January 7, 2009
Darren Kuropatwa
 

What's hot (20)

Diabolic Str8ts #3 and Weekly Extreme #63 - Solution
Diabolic Str8ts #3 and Weekly Extreme #63 - SolutionDiabolic Str8ts #3 and Weekly Extreme #63 - Solution
Diabolic Str8ts #3 and Weekly Extreme #63 - Solution
 
Series & Progression Mathematics
Series & Progression MathematicsSeries & Progression Mathematics
Series & Progression Mathematics
 
Expanding
ExpandingExpanding
Expanding
 
Inequalities day 1 worked
Inequalities day 1 workedInequalities day 1 worked
Inequalities day 1 worked
 
Unit 5.4
Unit 5.4Unit 5.4
Unit 5.4
 
Year 11 foundation pythagoras 1
Year 11 foundation pythagoras 1Year 11 foundation pythagoras 1
Year 11 foundation pythagoras 1
 
4.9 Graphing Quadratic Inequalities
4.9 Graphing Quadratic Inequalities4.9 Graphing Quadratic Inequalities
4.9 Graphing Quadratic Inequalities
 
Level 4 a1
Level 4 a1Level 4 a1
Level 4 a1
 
Math is Awesome ACT Prep
Math is Awesome ACT PrepMath is Awesome ACT Prep
Math is Awesome ACT Prep
 
Numbers session 1 class 2
Numbers session 1 class 2Numbers session 1 class 2
Numbers session 1 class 2
 
Polynomials intro
Polynomials introPolynomials intro
Polynomials intro
 
Diabolic Str8ts #2
Diabolic Str8ts #2Diabolic Str8ts #2
Diabolic Str8ts #2
 
Sequence: Generating a Formula
Sequence: Generating a FormulaSequence: Generating a Formula
Sequence: Generating a Formula
 
Algebra 7 Point 6
Algebra 7 Point 6Algebra 7 Point 6
Algebra 7 Point 6
 
5.7 Quadratic Inequalities
5.7 Quadratic Inequalities5.7 Quadratic Inequalities
5.7 Quadratic Inequalities
 
Mathnasium Presentation (1)
Mathnasium Presentation (1)Mathnasium Presentation (1)
Mathnasium Presentation (1)
 
Group activity
Group activityGroup activity
Group activity
 
Str8ts Weekly Extreme #53 - Solution
Str8ts Weekly Extreme #53 - SolutionStr8ts Weekly Extreme #53 - Solution
Str8ts Weekly Extreme #53 - Solution
 
Nikhil number pattern formulas
Nikhil number pattern formulasNikhil number pattern formulas
Nikhil number pattern formulas
 
Applied 20S January 7, 2009
Applied 20S January 7, 2009Applied 20S January 7, 2009
Applied 20S January 7, 2009
 

Viewers also liked

Fabrizio politi sixhtcontinent il social economico
Fabrizio politi sixhtcontinent il social economicoFabrizio politi sixhtcontinent il social economico
Fabrizio politi sixhtcontinent il social economico
fabrizio politi
 
Profession gr
Profession grProfession gr
Profession gr
Aspa Tzavara
 
Hecho deportivo
Hecho deportivoHecho deportivo
Hecho deportivo
colegioandino
 
Портфолио - атестaционна карта
Портфолио -  атестaционна   картаПортфолио -  атестaционна   карта
Портфолио - атестaционна карта
Rose Sunrise
 
Пет картини_Георги Стоилов
Пет картини_Георги СтоиловПет картини_Георги Стоилов
Пет картини_Георги Стоилов
Мария Maria Georgieva TeacherBG
 
Δομή ακολουθίας στη ΓΛΩΣΣΑ
Δομή ακολουθίας στη ΓΛΩΣΣΑΔομή ακολουθίας στη ΓΛΩΣΣΑ
Δομή ακολουθίας στη ΓΛΩΣΣΑ
Alexandra Karakasidou
 
Math practice
Math practiceMath practice
Math practice
FRANCELIA CHAPA
 
Numeracy in the Classroom
Numeracy in the ClassroomNumeracy in the Classroom
Numeracy in the Classroom
Chris Harbeck
 
2nd Grade Mx Nov 09
2nd Grade Mx Nov 092nd Grade Mx Nov 09
2nd Grade Mx Nov 09
Laura Chambless
 
општество
општествоопштество
општество
brane71
 
Agentes y sistemas económicos
Agentes y sistemas económicosAgentes y sistemas económicos
Agentes y sistemas económicos
Izaskun Bereziartua Rojas
 
Biologi : GERAK PADA TUMBUHAN
Biologi : GERAK PADA TUMBUHANBiologi : GERAK PADA TUMBUHAN
Biologi : GERAK PADA TUMBUHAN
Adinda Gifary
 
Jазик
JазикJазик
Jазик
Biljana CM
 
Работен лист проценти / дропки / децимали
Работен лист   проценти / дропки / децималиРаботен лист   проценти / дропки / децимали
Работен лист проценти / дропки / децимали
Biljana CM
 
Cse 627 presentation
Cse 627 presentationCse 627 presentation
Cse 627 presentation
Katie Smart
 
работен лист придавки и именки BiljanaCM
работен лист придавки и именки BiljanaCMработен лист придавки и именки BiljanaCM
работен лист придавки и именки BiljanaCM
Biljana CM
 
00 дијагностички тест македонски јазик Biljana Curlevska Man...
00        дијагностички      тест      македонски јазик Biljana Curlevska Man...00        дијагностички      тест      македонски јазик Biljana Curlevska Man...
00 дијагностички тест македонски јазик Biljana Curlevska Man...
Biljana CM
 

Viewers also liked (17)

Fabrizio politi sixhtcontinent il social economico
Fabrizio politi sixhtcontinent il social economicoFabrizio politi sixhtcontinent il social economico
Fabrizio politi sixhtcontinent il social economico
 
Profession gr
Profession grProfession gr
Profession gr
 
Hecho deportivo
Hecho deportivoHecho deportivo
Hecho deportivo
 
Портфолио - атестaционна карта
Портфолио -  атестaционна   картаПортфолио -  атестaционна   карта
Портфолио - атестaционна карта
 
Пет картини_Георги Стоилов
Пет картини_Георги СтоиловПет картини_Георги Стоилов
Пет картини_Георги Стоилов
 
Δομή ακολουθίας στη ΓΛΩΣΣΑ
Δομή ακολουθίας στη ΓΛΩΣΣΑΔομή ακολουθίας στη ΓΛΩΣΣΑ
Δομή ακολουθίας στη ΓΛΩΣΣΑ
 
Math practice
Math practiceMath practice
Math practice
 
Numeracy in the Classroom
Numeracy in the ClassroomNumeracy in the Classroom
Numeracy in the Classroom
 
2nd Grade Mx Nov 09
2nd Grade Mx Nov 092nd Grade Mx Nov 09
2nd Grade Mx Nov 09
 
општество
општествоопштество
општество
 
Agentes y sistemas económicos
Agentes y sistemas económicosAgentes y sistemas económicos
Agentes y sistemas económicos
 
Biologi : GERAK PADA TUMBUHAN
Biologi : GERAK PADA TUMBUHANBiologi : GERAK PADA TUMBUHAN
Biologi : GERAK PADA TUMBUHAN
 
Jазик
JазикJазик
Jазик
 
Работен лист проценти / дропки / децимали
Работен лист   проценти / дропки / децималиРаботен лист   проценти / дропки / децимали
Работен лист проценти / дропки / децимали
 
Cse 627 presentation
Cse 627 presentationCse 627 presentation
Cse 627 presentation
 
работен лист придавки и именки BiljanaCM
работен лист придавки и именки BiljanaCMработен лист придавки и именки BiljanaCM
работен лист придавки и именки BiljanaCM
 
00 дијагностички тест македонски јазик Biljana Curlevska Man...
00        дијагностички      тест      македонски јазик Biljana Curlevska Man...00        дијагностички      тест      македонски јазик Biljana Curlevska Man...
00 дијагностички тест македонски јазик Biljana Curlevska Man...
 

Similar to Sudoku

Chapter 1 Assignment Problems (DS) (1).pptx
Chapter 1 Assignment Problems (DS) (1).pptxChapter 1 Assignment Problems (DS) (1).pptx
Chapter 1 Assignment Problems (DS) (1).pptx
PriyankaLunavat
 
Sudoku
SudokuSudoku
Calculation techniques in numbers
Calculation techniques in numbersCalculation techniques in numbers
Calculation techniques in numbers
sealih
 
just reference
just referencejust reference
just reference
Sumin Kim
 
basics
basicsbasics
basics
Sumin Kim
 
upload
uploadupload
upload
Sumin Kim
 
Basic math
Basic mathBasic math
Basic math
FathimaRifa
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
Muhammad Hammad Waseem
 
Fraction
FractionFraction
Fraction
mikealabacus
 
Fraction
FractionFraction
Fraction
mikealabacus
 
Onlinetest360.com quantitative aptitude PDF
Onlinetest360.com quantitative aptitude PDFOnlinetest360.com quantitative aptitude PDF
Onlinetest360.com quantitative aptitude PDF
onlinetest
 
Math trick
Math trickMath trick
Math trick
Aisyah Siti
 
Math trick
Math trickMath trick
Math trick
karinasitip
 
Math Trick
Math TrickMath Trick
Math Trick
Sindy Ma'rufah
 
Math review
Math reviewMath review
Math review
BenjaminMadrigal4
 
The rules of indices
The rules of indicesThe rules of indices
The rules of indices
Yu Kok Hui
 
Topik 1
Topik 1Topik 1
Decimal lattice multiplication
Decimal lattice multiplicationDecimal lattice multiplication
Decimal lattice multiplication
Kevin Cummins
 
CSE031.Lecture_07-FlowCharts_Pseudocode .Part_II.pdf
CSE031.Lecture_07-FlowCharts_Pseudocode .Part_II.pdfCSE031.Lecture_07-FlowCharts_Pseudocode .Part_II.pdf
CSE031.Lecture_07-FlowCharts_Pseudocode .Part_II.pdf
NourhanTarek23
 
Basic Math review sheet.pdf
Basic Math review sheet.pdfBasic Math review sheet.pdf
Basic Math review sheet.pdf
Noraima2
 

Similar to Sudoku (20)

Chapter 1 Assignment Problems (DS) (1).pptx
Chapter 1 Assignment Problems (DS) (1).pptxChapter 1 Assignment Problems (DS) (1).pptx
Chapter 1 Assignment Problems (DS) (1).pptx
 
Sudoku
SudokuSudoku
Sudoku
 
Calculation techniques in numbers
Calculation techniques in numbersCalculation techniques in numbers
Calculation techniques in numbers
 
just reference
just referencejust reference
just reference
 
basics
basicsbasics
basics
 
upload
uploadupload
upload
 
Basic math
Basic mathBasic math
Basic math
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
 
Fraction
FractionFraction
Fraction
 
Fraction
FractionFraction
Fraction
 
Onlinetest360.com quantitative aptitude PDF
Onlinetest360.com quantitative aptitude PDFOnlinetest360.com quantitative aptitude PDF
Onlinetest360.com quantitative aptitude PDF
 
Math trick
Math trickMath trick
Math trick
 
Math trick
Math trickMath trick
Math trick
 
Math Trick
Math TrickMath Trick
Math Trick
 
Math review
Math reviewMath review
Math review
 
The rules of indices
The rules of indicesThe rules of indices
The rules of indices
 
Topik 1
Topik 1Topik 1
Topik 1
 
Decimal lattice multiplication
Decimal lattice multiplicationDecimal lattice multiplication
Decimal lattice multiplication
 
CSE031.Lecture_07-FlowCharts_Pseudocode .Part_II.pdf
CSE031.Lecture_07-FlowCharts_Pseudocode .Part_II.pdfCSE031.Lecture_07-FlowCharts_Pseudocode .Part_II.pdf
CSE031.Lecture_07-FlowCharts_Pseudocode .Part_II.pdf
 
Basic Math review sheet.pdf
Basic Math review sheet.pdfBasic Math review sheet.pdf
Basic Math review sheet.pdf
 

Recently uploaded

How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 

Recently uploaded (20)

How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 

Sudoku

  • 1. SOLVING SUDOKU Graham Hutton University of Nottingham (with thanks to Richard Bird)
  • 2. 2 What is Sudoku? A simple but addictive puzzle, invented in the USA in 1979 and called Number Place; Became popular in Japan in 1986, where it was renamed Sudoku (~ “single number”); First appeared in UK newspapers in 2004, and became an international craze in 2005.
  • 3. 3 Example Fill in the grid so that every row, column and box contains each of the numbers 1 to 9: 2 1 3 8 5 7 6 1 3 9 8 1 2 5 7 3 1 8 9 8 2 5 6 9 7 8 4 4 2 5
  • 4. 4 Example Fill in the grid so that every row, column and box contains each of the numbers 1 to 9: 2 1 3 8 5 7 6 1 3 9 8 1 2 5 7 3 1 8 9 8 2 5 6 9 7 8 4 4 2 5 What number must go here?
  • 5. 5 Example Fill in the grid so that every row, column and box contains each of the numbers 1 to 9: 2 1 3 8 5 7 6 1 3 9 8 1 2 5 7 3 1 8 9 8 2 5 6 9 7 8 4 4 2 5 1, as 2 and 3 already appear in this column. 1
  • 6. 6 Example Fill in the grid so that every row, column and box contains each of the numbers 1 to 9: 2 1 3 8 5 7 6 1 3 9 8 1 2 5 7 3 1 8 9 8 2 1 5 6 9 7 8 4 4 2 5
  • 7. 7 Example Fill in the grid so that every row, column and box contains each of the numbers 1 to 9: 2 1 3 8 5 7 6 1 3 9 8 1 2 5 7 3 1 8 9 8 2 1 5 6 9 7 8 4 4 2 5 3
  • 8. 8 Example Fill in the grid so that every row, column and box contains each of the numbers 1 to 9: 2 1 3 8 5 7 6 1 3 9 8 1 2 5 7 3 1 8 9 8 2 1 5 3 6 9 7 8 4 4 2 5
  • 9. 9 Example Fill in the grid so that every row, column and box contains each of the numbers 1 to 9: 2 1 3 8 5 7 6 1 3 9 8 1 2 5 7 3 1 8 9 8 2 1 5 3 6 9 7 8 4 4 2 5 2
  • 10. 10 Example Fill in the grid so that every row, column and box contains each of the numbers 1 to 9: 2 1 3 8 5 7 6 1 3 9 8 1 2 5 7 3 1 8 9 8 2 1 5 2 3 6 9 7 8 4 4 2 5 And so on…
  • 11. 11 Example Fill in the grid so that every row, column and box contains each of the numbers 1 to 9: 2 4 9 5 7 1 6 3 8 8 6 1 4 3 2 9 7 5 5 7 3 9 8 6 1 4 2 7 2 5 6 9 8 4 1 3 6 9 8 1 4 3 2 5 7 3 1 4 7 2 5 8 6 9 9 3 7 8 1 4 2 5 6 1 5 2 3 6 9 7 8 4 4 8 6 2 5 7 3 9 1 The unique solution for this easy puzzle.
  • 12. 12 This Talk We show how to develop a program that can solve any Sudoku puzzle in an instant; Start with a simple but impractical program, which is improved in a series of steps; Emphasis on pictures rather than code, plus some lessons about algorithm design.
  • 13. 13 Representing a Grid type Grid = Matrix Char type Matrix a = [Row a] type Row a = [a] A grid is essentially a list of lists, but matrices and rows will be useful later on.
  • 14. 14 Examples easy :: Grid easy = [ "2 1 38" , " 5" , " 7 6 " , " 13 " , " 981 257" , "31 8 " , "9 8 2 " , " 5 69784" , "4 25 " ] empty :: Grid empty = replicate 9 (replicate 9 ' ')
  • 15. 15 Extracting Rows rows :: Matrix a → [Row a] rows m = m 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
  • 16. 16 … Columns cols :: Matrix a → [Row a] cols m = transpose m 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16
  • 17. 17 … And Boxes boxs :: Matrix a → [Row a] boxs m = <omitted> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 5 6 3 4 7 8 9 10 13 14 11 12 15 16
  • 18. 18 Validity Checking Let us say that a grid is valid if it has no duplicate entries in any row, column or box: valid :: Grid → Bool valid g = all nodups (rows g) ∧ all nodups (cols g) ∧ all nodups (boxs g) A direct implementation, without concern for efficiency.
  • 19. 19 Making Choices Replace each blank square in a grid by all possible numbers 1 to 9 for that square: choices :: Grid → Matrix [Char] 1 2 3 4 5 6 3 7 8 9 1 2 3 4 4 5 6 7 8 9 3 4
  • 20. 20 Collapsing Choices Transform a matrix of lists into a list of matrices by considering all combinations of choices: collapse :: Matrix [a] → [Matrix a] 1 3 4 1 2 3 4 2 2 3 4 1 1 3 4 2 1 2 3 4 1 2
  • 21. 21 A Brute Force Solver solve :: Grid → [Grid] solve = filter valid . collapse . choices Consider all possible choices for each blank square, collapse the resulting matrix, then filter out the valid grids.
  • 22. 22 Does It Work? > solve easy ERROR: out of memory Simple, but impractical! The easy example has 51 blank squares, resulting in 951 grids to consider, which is a huge number: 463839768658810197932815016789059145431896769800 9
  • 23. 23 Reducing The Search Space Many choices that are considered will conflict with entries provided in the initial grid; For example, an initial entry of 1 precludes another 1 in the same row, column or box; Pruning such invalid choices before collapsing will considerably reduce the search space.
  • 24. 24 Pruning Remove all choices that occur as single entries in the corresponding row, column or box: prune :: Matrix [Char] → Matrix [Char] 1 1 2 4 1 3 3 4 1 2 4 3 3 4
  • 25. 25 And Again Pruning may leave new single entries, so it makes sense to iterate the pruning process: 1 2 4 3 3 4
  • 26. 26 And Again Pruning may leave new single entries, so it makes sense to iterate the pruning process: 1 2 4 3 4
  • 27. 27 And Again Pruning may leave new single entries, so it makes sense to iterate the pruning process: 1 2 3 4
  • 28. 28 And Again Pruning may leave new single entries, so it makes sense to iterate the pruning process: 1 2 3 4 We have now reached a fixpoint of the pruning function.
  • 29. 29 An Improved Solver solve’ :: Grid → [Grid] solve’ = filter valid . collapse . fix prune . choices For the easy example, the pruning process alone is enough to completely solve the puzzle: > solve’ easy Terminate s instantly!
  • 30. 30 But… > solve' gentle No solution after two hours - we need to think further! For a gentle example, pruning leaves around 381 grids to consider, which is still a huge number: 44342648824303776994824963061914989280 3
  • 31. 31 Reducing The Search Space After pruning there may still be many choices that can never lead to a solution; But such bad choices will be duplicated many times during the collapsing process; Discarding these bad choices is the key to obtaining an efficient Sudoku solver.
  • 32. 32 Blocked Matrices Let us say that a matrix is blocked if some square has no choices left, or if some row, column, or box has a duplicated single choice: Key idea - a blocked matrix can never lead to a solution. 1 1 2 1 3 4 3
  • 33. 33 Expanding One Choice Transform a matrix of lists into a list of matrices by expanding the first square with choices: expand :: Matrix [a] → [Matrix [a]] 1 2 3 4 1 2 2 3 4 1 2 1 3 4 1 2
  • 34. 34 Our Final Solver solve’’ :: Grid → [Grid] solve’’ = search . prune . choices search :: Matrix [Char] → [Grid] search m | blocked m = [] | complete m = collapse m | otherwise = [g | m' ← expand m , g ← search (prune m')]
  • 35. 35 Notes Using fix prune rather than prune makes the program run slower in this case; No need to filter out valid grids, because they are guaranteed to be valid by construction; This program can now solve any newspaper Sudoku puzzle in an instant!
  • 36. 36 The Result This program has saved my life - my Sudoku addiction is finally cured!! Subliminal Message Haskell is the world's greatest programming language.