Sudoku Solver

































I recently had a big exam/board to sit with the Navy, and had to come up with a whole new level of procrastination to prevent myself doing revision.

The result is a Matlab Sudoku Solver. You can download it as a zip file here. (right click, save target as). You will need Matlab version 6.5 or above to run this.

Below is a brief description of how it works...

Main Variables:

S is a 9x9 array, equating to the sudoku. Enter your sudoku in s0.m, with a zero in each of the 'empty' boxes.

M is a 9x9x9 array. Each layer of the array represents a number. Within the layer, a 1 in a cell means that that number could appear there, and a 0 means it has been ruled out.

Executable File:

S0.m is the executable file. You need to edit it first to enter your Sudoku (it will be obvious how to do this). 'S0.m' defines the main variables and runs the function 'Sudoku.m'. Once it has either completed the sudoku or got stuck, it will display the current state of the sudoku using 'Sdisp.m'.

Display File:

Sudoku.fig Open this before you run 's0.m' and it will make the display a bit more legible. Trust me!

Functions:

Sudoku.m Pretty much runs the show. It runs each of the 'Rules' in turn, and updates the 'M' array by calling 'update.m' every time a number has been added to the sudoku. It continues to run until it has completed the Sudoku or it fails to get any further with solving the sudoku. It prints 'n', the number of times through it has run.

Update.m If a number has been added to a cell in the sudoku, it simply says that number can't appear again in that row, column or square. Also, no other number can appear in the same cell as it is taken.

Flip.m All rules are applied to rows and columns. Instead of writing each function out twice, I simply flip the 'S' and 'M' arrays along the i=j axis so that rows become columns! I then run the rule again and flip the arrays back to their original state.

Sdisp.m Displays the sudoku in its current state. If it is incomplete then it shows where it has got to. Dots represent where numbers could be. (dots are in positions as on a mobile phone keypad, with 1 in the top left and 9 in the bottom right)

Sdispn.m Not used in the normal running of the program, but you can run it yourself from the command window. It displays the current state for a particular number. Run as follows: '>> sdispn(s,m,5) ' if you wish to see where is is possible for 5s to be.

Rule1.m to Rule 3.m The basic rules. Fill in a number when theres only one possible place for it to be or only one possible number for a place. Always followed by 'Update.m' to update 'M' accordingly.

Rule5.m to Rule 10.m The trickier rules. Remove 'dots' (1s from the 'M' array).



Entering the Sudoku (this is a Times 'Fiendish' one):





The Result: