Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Algorithms & AI » Using Genetic Algorithms to come up with Sudoku Puzzles

Using Genetic Algorithms to come up with Sudoku Puzzles

Sudoku is a new type of puzzle from Japan that will keep you entertained for a time and may even get you hooked. This article demonstrates how to generate a fully populated Sudoku grid using genetic algorithms.

Author Rank :
Page Views : 92323
Downloads : 2914
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Sudoku.ZIP
 
 
DevExpress Free UI Controls
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Sudoku.jpg

Figure 1 - Best Sudoku Genome from Generation 900

Well there is a new craze here in New York City... Sudoku.  You see it in the bookstores, the subways, and on the newstands.   The closest analogy  I can come up with to describe Sudoku is the Rubicks Cube , but easier.  The way Sudoku works is you are given a grid like the one shown in figure 2 containing numbers.   The object of Sudoku is to fill the grid with all the numbers in such a way that each row, column, and 3x3 bold square has a unique numbers 1-9.   There exists only one solution to the puzzle, so when you finish the puzzle you can check it against an answer key.  If you are interested in Sudoku, you can go to the website http://www.sudoku.com/ and check it out.

puzzle.jpg

Figure 2 - Sample Sudoku puzzle

Having gotten a little hooked on these brain-spinning puzzles myself,  I decided to write a genetic algorithm to create possible Sudoku solutions.  It took a while, but I finally came up with a fitness function, mutation, and crossover function that would help produce a solution as shown in figure 3.  Note that it took many, many generations to arrive at a unique solution for the gene population, but eventually it does happen. (A fitness of -->1 indicates that we finally found a Sudoku Square).

Figure2.jpg

Figure 3 - Sudoku Solution after 36,700 generations of genes

Design

The Design was taken from the Genetic Algorithm Mastermind article and adapted to produce a Sudoku Genomes.  The SudokuGenome contains a 9x9 rectangular integer array.  The Genome can do basic GA functions such as Mutate, Crossover, Calculate Fitness, and Initialize.  The Population class contains the gene pool and can manipulate the genes in the pool to produce the next generation.  If you want to understand more about Genetic Algorithms, please read my article on the subject on C# Corner, Implementing a Genetic Algorithms in C# and .NET. 

SudokuUML.jpg

Figure 4 - UML Design Reverse Engineered using WithClass

Fitness Function

As always, coming up with the proper fitness function for the genetic algorithm is the greatest challenge.  The way we determined the fitness function was using three hashtables that act as histograms.  The fitness algorithm first goes through each column of the Sudoku Genome and uses the number contained in the cell as a hash key.  A value is added to the ColumnMap with the hash key in each cell.  After an  entire column is traversed, the algorithm looks at the count of the ColumnMap .  If every key in the column is unique, then the ColumnMap contains a total of 9 values.  If the column contains a few duplicates, the total count in the ColumnMap will always be less than 9.  The count can then be used as a representative fitness of uniqueness for a particular column.  By adding this number for all columns, we can come up with a fitness for uniqueness of columns.  We can then perform the same exact technique for determining row uniqueness.  The RowMap is populated with keys from each cell in a row of the Sudoku grid.  If the row is entirely unique, then the RowMap will contain 9 entries.   The same technique is also used for each 3x3 cell grouping (shown in figure 1).  The SquareMap is populated with cell values as keys for this hashtable.  Listing 1 demonstrates the entire fitness function operating  on our Sudoku Gene's Multidimensional Array.

Listing 1 - Fitness function for the Sudoku Grid


///
<summary>
/// The Calculate Sudoku Fitness uses the uniqueness of columns, rows
/// and 3x3 squares in the grid to determine a fitness value
/// </summary>
/// <returns></returns>
private float CalculateSudokuFitness()
{
// set fitnesses for columns, rows, and squares initially to 0
float fitnessColumns = 0;
float fitnessRows = 0;
float fitnessSquares = 0;
// go through each column
for (int i = 0; i < 9; i++)
{
// Go through each cell in a column, add it to the ColumnMap according
// to the cell value
ColumnMap.Clear(); // clear the column map for each new column
for (int j = 0; j < 9; j++)
{
// check for uniqueness in row
if (ColumnMap[TheArray[i,j]] == null)
{
ColumnMap[TheArray[i,j]] = 0;
}
ColumnMap[TheArray[i,j]] = ((
int)ColumnMap[TheArray[i,j]]) + 1;
}
// accumulate the column fitness based on the number of entries in the ColumnMap
fitnessColumns += (float)(1.0f/ (10-ColumnMap.Count))/9.0f;
//fitnessColumns += (float)Math.Exp(ColumnMap.Count*10 - 90)/9;
}
// go through each row next
for (int i = 0; i < 9; i++)
{
// Go through each cell in a row, add it to the RowMap according
// to the cell value
RowMap.Clear(); // clear the row map for each new row
for (int j = 0; j < 9; j++)
{
// check for uniqueness in row
if (RowMap[TheArray[j,i]] == null)
{
RowMap[TheArray[j,i]] = 0;
}
RowMap[TheArray[j,i]] = ((
int)RowMap[TheArray[j,i]]) + 1;
}
// accumulate the row fitness based on the number of entries in the RowMap
fitnessRows += (float)(1.0f/ (10-RowMap.Count))/9.0f;
// fitnessRows += (float)Math.Exp(RowMap.Count*10 - 90)/9;
}
// go through next square
for (int l = 0; l < 3; l++)
{
for (int k = 0; k < 3; k++)
{
// Go through each cell in a 3 x 3 square, add it to the SquareMap according
// to the cell value
SquareMap.Clear(); // Clear the square map for each 3 x 3 square
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
// check for uniqueness in row
// check for uniqueness in row
if (SquareMap[TheArray[i + k*3,j + l*3]] == null)
{
SquareMap[TheArray[i+k*3,j+l*3]] = 0;
}
// accumulate the square fitness based on the number of entries in the SquareMap
SquareMap[TheArray[i + k*3,j + l*3]] = ((int)SquareMap[TheArray[i + k*3,j + l*3]]) + 1;
}
}
fitnessSquares += (
float)(1.0f/ (10-SquareMap.Count))/9.0f;
}
}
// The fitness of the entire Sudoku Grid is the product
// of the column fitness, row fitness and 3x3 square fitness
CurrentFitness = fitnessColumns * fitnessRows * fitnessSquares;
return CurrentFitness;
}

Conclusion

Sudoku is the latest fad for puzzle addicts and I suspect it's here to stay.  This article demonstrates how to generate a fully populated Sudoku puzzle using a genetic algorithm.  In our next article we will tackle solving actual Sudoku Puzzles with GA's like the one shown in figure 2.  In the meantime, you can wipe that puzzled  expression off your face, and delve into Sudoku in the land of C# and .NET.

Affiliates

Sudoku for Kids - 120 Printable Puzzles

Sudoku Secrets

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mike Gold

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems.

He can be reached at mike@c-sharpcorner.com

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
givens by ana On January 26, 2008
how many given numbers did you use in your puzzle? and how did you ensure constraints are met regarding these gives (i.e.that teir position is not changed by crossover and mutation)? thanks
Reply | Email | Modify 
Very Slow by Disco On September 18, 2009
This algorithm is very slow. I wrote one in C that took about 20ms to create a 9X9 sudoku solution. I was looking for a faster one, because I tried to make it create a 16X16 puzzle, but it took forever to do that.

All mine did was:

for each row
   for each col
      generate a list of valid possibilities for this cell
      if the list is empty, start again.
      else pick one at random, insert it into the cell.

It's a lot simpler that the algorithm in this article.
Reply | Email | Modify 
Re: Very Slow by Mike On February 23, 2011
agreed, it is definitely not the optimal way to generate a sudoku puzzle, but it does show you the power of genetic algorithms to be able to tackle the problem. Genetic algorithms work for multiple problem domains, where as your solution only works for sudoku.
Reply | Email | Modify 
Error!!! by Bruno On May 16, 2011
When i try to run your game, i have a error.... this "A operação entre threads não é válida: controlo 'statusBar1' acedido a partir de um thread diferente do thread onde foi criado." The operation between threads is not valid: Control 'StatusBar1' accessed from a different thread where the thread was created.
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.