Alan Swindells' Blog

Tuesday, June 24, 2014

Simple fast sudoku solver in c#

Sudoku solver

I've written a few of these in my time in various languages from VBA in Excel through to Smalltalk. Mostly I adopt a method of trying a few different simple heuristics and resorting to a recursive backtracking method if they fail. The typical outline is something like this:

Solve (game)
   if game is complete return SUCCESS

   if heuristic 1 works
       return Solve (game)
   if heuristic 2 works
       return Solve (game)
   ...
 
   if heuristic n works
       return Solve (game)

   choose next empty cell
       for each valid number for this cell
             if Solve (game) then return SUCCESS
       next

    return FAILURE

This works well and using heuristics such as identifying cells that can only take one value or identifying where a value only appears once in a row or column or square are enough to solve the board very rapidly. The nice thing about the above algorithm is that you can easily maintain complex state information about the board and just copy that over to the next call letting the stack do all the work for you instead of having to restore the state.

Dumbed down solver

For this version I decided to take a very simple approach with no heuristics and just trying all valid numbers in each successive square. I also converted the more elegant and simple recursive approach to an iterative approach and make the whole thing as "stateless" as possible. Here is the result...

using System;
using System.Collections.Generic;
using System.Linq;

namespace Sudoku
{
    class Program
    {
        static int[,] groups = new int[81, 20];

        static void Setup()
        {
            //for each square, create a list of all the related squares and store in groups[]
            int [] start = new [] {0, 3, 6, 27, 30, 33, 54, 57, 60};    //top left of each square
            int [] index = new [] {0, 1, 2, 9, 10, 11, 18, 19, 20};     //offset for 9 elements of square

            for (int r = 0; r < 9; r++)
            {
                for (int c = 0; c < 9; c++)
                {
                    int k = start[c / 3 + 3 * (r / 3)];     //start of square that this r,c belongs to 

                    List<int> tmp = new List<int>();

                    for (int i = 0; i < 9; i++)
                    {
                        tmp.Add(i + r * 9);         //row
                        tmp.Add(c + i * 9);         //column
                        tmp.Add(k + index[i]);      //square
                    }

                    tmp = tmp.Distinct().ToList();
                    int s = c + r * 9;
                    tmp.Remove(s);
                    
                    for (int i = 0; i < tmp.Count(); i++) groups[s, i] = tmp[i];
                }
            }
          }

        static int[] Solve(int[] grid)
        {
            int[] b = new int[81];
            List<int>[] valid = new List<int>[81];

            int [] empty = new int[81];
            int numEmpty = 0;

            for (int i = 0; i < 81; i++)
            {
                b[i] = grid[i];
                if (b[i] == 0) empty[numEmpty++] = i;
            }

            int nodes = 0;

            int s = 0;

            //create list of valid numbers for square s by eliminating all numbers in related squares
            valid[empty[s]] = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
            for (int i = 0; i < 20; i++) valid[empty[s]].Remove(b[groups[empty[s], i]]);

            while (s < numEmpty && s >= 0)
            {
                if (valid[empty[s]].Count > 0)
                {
                    nodes++;

                    b[empty[s]] = valid[empty[s]].ElementAt(0);
                    valid[empty[s]].RemoveAt(0);
                    s++;

                    if (s < numEmpty)
                    {
                        valid[empty[s]] = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                        for (int i = 0; i < 20; i++) valid[empty[s]].Remove(b[groups[empty[s], i]]);
                    } 
                }
                else
                {
                    b[empty[s]] = 0;
                    s--;
                }
            }

            return b;
        }

        static void Main(string[] args)
        {
            Setup();

            int[] b = Solve(new int[] {3, 0, 0, 9, 0, 7, 1, 8, 0, 0, 0, 0, 0, 3, 4, 0, 0, 0, 0, 0, 5, 1, 0, 0, 0, 3, 0, 6, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0, 5, 0, 0, 2, 0, 0, 0, 0, 0, 3, 0, 9, 0, 3, 0, 0, 0, 1, 7, 0, 0, 0, 0, 0, 4, 9, 0, 0, 0, 0, 0, 2, 4, 7, 0, 8, 0, 0, 0});

            for (int r = 0; r < 9; r++)
            {
                string s = "";

                for (int c = 0; c < 9; c++)
                {
                    int i = c + r * 9;
                    s = s + b[i].ToString() + " ";
                }

                Console.WriteLine(s);
            }
            Console.ReadKey();
        }

    }
}

The program has a small setup section that need only be run once. It sets up an array containing all the related cells for every cell in turn. That means all the cells that are in either the same row, column or 9-square. Note that there are only 20 related cells: 8 within the 9-square and 6 for each of row and column.

I ran some tests and on my (not very up-to-date) machine it solved 100 puzzles in about 3.5 seconds, so 35 hundredths of a second per solution.

Dancing Links, Graph Theory and the 4 Colour problem

Apparently the standard way of solving a problem like this is to using a method based on doubly-linked lists called "Dancing Links" (coined by Knuth). I haven't looked into how that works and how much improvement it would offer although I believe I read that it halved the time for the solution to a related problem.

Sudoku belongs to the same set of problems as the famous 4 colour problem. The 4 colour theorem (no longer a conjecture since it was proved... although there are some sections of the maths community that are less than satisfied since the proof relied heavily of computational aids) states that it is always possible to colour a map so that every region is a different colour to it's neighbouring regions using only 4 colours. This problem can be reformulated as a graph where each of the regions represents a node and the connections represent the boundaries. Now you need to ensure that all connected nodes have a different label (colour).

The Sudoku problem can be reformulated in a similar way. Each cell represents a node is connected to the 20 related cells. That means 81 nodes and 810 connections (1/2 * 81 * 20),  i.e. every node has 20 connections, but a->b is the same as b->a so we need to half the count.

I've not looked at whether there are standard graph colouring algorithms that can help, but I suspect not since they would necessarily cater for more general problems, i.e. without the high degree of structure in Sudoku.

Saturday, February 14, 2009

XNA Pool game development

XNA / C# Pool game

After downloading the XNA dev suite and playing around with some of the samples I've decided to learn some C# / XNA and I thought the best way of doing it would be to create a game. Before I continue, I should state that this is my first attempt at blogging anything so it will be pretty remedial, but hopefully I'll improve as a go.

First of all, I should say that I owe a lot to Riemer Grootjans and his brilliant XNA Game series (here). This guy is a legend and I strongly recommend anyone interested in XNA to read his online tutorials or buy his book.

Starting out: Walk through of first cut

All of the coding I have done on this project so far is very straightforward, so I'll just dump it here and add commentary in red italics:

First of all we need to add some content:

Pool table model - "pool table.x" - taken from the Google SketchUp library here (this needs coverting to a .x format)
Pool ball model - "SphereHighPoly.fbx" - taken from the XNA Creators Club online tutorial here
Pool ball textures - you can create these in any bitmap editor. Just crate a bitmap whose height is half it's width. After filling the correct colour create a white circle in the centre approx 1/7th of the height and add the ball number. For the stripes, clear bands above and below, leaving a central band of about 20%-25% of the area. Name the files Ball0.bmp - Ball15.bmp (or other file extension).

Add this content to your solution.


The usual XNA using statements:


using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

The following declares the PoolGame class and it's members. Most of these will be self explanatory or else explained as I go. Note that I am using a class called "Ball" which I'll come to later:

namespace Pool
{
public class PoolGame : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
Effect effect;
Matrix viewMatrix;
Matrix projectionMatrix;
Vector3 camera = new Vector3(0f, 30f, 0.01f);
Random rand = new Random();
Ball[] balls = new Ball[16];
Model tableModel;
float viewAngle1 = 2;
float viewAngle2 = -MathHelper.PiOver2;
float viewDist = 80;
Vector3 tableCentre;
Vector3 tableScale;
float tableWidth;
float tableLength;
float ballScale;

Standard constructor instatiates the Graphics device manager and sets the content path.

public PoolGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}


Initialisation. I’ve added some temp code that just sets up the ball positions, orientations and velocities.


protected override void Initialize()
{
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 800;
graphics.IsFullScreen = false;
graphics.ApplyChanges();
Window.Title = "Alan's Pool";

//Temp!!
float maxSpeed = 20;

foreach (Ball ball in balls)
{
ball.velocity = new Vector3((float)rand.NextDouble() * 2f * maxSpeed - maxSpeed, 0f, (float)rand.NextDouble() * 2f * maxSpeed - maxSpeed);
ball.position = Vector3.Zero;
ball.angularVelocity = Quaternion.Identity();
}

base.Initialize();
}

Now load content.I’m loading in 2 models, one for the ball which is just a sphere and one for the pool table. I’ve taken these models from free online sources, but they can be created in a 3d design application, such as belnder. I also load in a different texture for each of the balls, these textures are just bitmaps of the 15 different pool balls and simple to create. Here I set the static ballRadius member of the Ball class (defined below) – this is the same for all balls in my game and will be used later.


protected override void LoadContent()
{
device = graphics.GraphicsDevice;

LoadBallContent();

tableModel = Content.Load<Model>("pool table");
tableScale = new Vector3(.5f, .5f, .5f);
tableCentre = new Vector3(114f * tableScale.X, -30.6f, 63.6f * tableScale.Z);
tableWidth = 12f;
tableLength = tableWidth * 8f / 4f;

projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 1000.0f);
}
public void LoadBallContent()
{
Ball.model = Content.Load<Model>("SphereHighPoly");
ballScale = .9f;
Ball.ballRadius = ballScale * Ball.model.Meshes[0].BoundingSphere.Radius;

for (int i = 0; i <= 15; i++)
{
balls[i] = new Ball();
balls[i].texture = Content.Load<Texture2D>("Ball" + String.Format("{0:d}", i));
}
}

The Draw function. We first set up up the view matrix, since it remains the same throughout the draw, then we call DrawTable() and then DrawBall() for each of the balls. In creating the view matrix, I’m going to use a camera that can zoom in and out (viewDist) and also rotate around the table (viewAngle2) and up and over the table (viewAngle1). I’m just using the standard polar coordinate transformation to achieve this:

x = r sin(phi) cos(theta)
y = r sin(phi) sin(theta)
z = r cos(phi)

In our case z and y are transposed and phi corresponds to viewAngle1, theta corresponds to viewAngle2 and r to viewDist.


protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.White);
camera = new Vector3(viewDist * (float)Math.Sin(viewAngle1) * (float)Math.Cos(viewAngle2),
-viewDist * (float)Math.Cos(viewAngle1),
viewDist * (float)Math.Sin(viewAngle1) * (float)Math.Sin(viewAngle2));
viewMatrix = Matrix.CreateLookAt(camera, new Vector3(0, 0, 0), new Vector3(0, 1, 0));

for (int i = 0; i < 16; i++) DrawBall(i, gameTime);

DrawTable();

base.Draw(gameTime);
}

Drawing the balls. Now we load the model mesh, use the ball positions, orientation (and scale) parameters to create the world matrix transformation, set the texture and draw.

public void DrawBall(int ball)
{
ModelMesh mesh = Ball.model.Meshes[0];
Matrix worldMat = Matrix.CreateScale(ballScale)
* Matrix.CreateFromQuaternion(balls[ball].orientation)
* Matrix.CreateTranslation(balls[ball].position);

foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.View = viewMatrix;
effect.Projection = projectionMatrix;
effect.World = worldMat;
effect.Texture = balls[ball].texture;
effect.TextureEnabled = true;
}

mesh.Draw();

}

Similar to drawing a ball, load the model, create the world transform and draw.

public void DrawTable()
{
ModelMesh mesh = tableModel.Meshes[0];
Matrix worldMat = Matrix.CreateTranslation(tableCentre)
* Matrix.CreateScale(tableScale) * Matrix.CreateRotationY(MathHelper.PiOver2);

foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.View = viewMatrix;
effect.Projection = projectionMatrix;
effect.World = worldMat;
}

mesh.Draw();
}

Now let's add in some keyboard control to move the camera around. I also call UpdateBalls() from here to step the simulation.

protected override void Update(GameTime gameTime)
{
KeyboardState kbs = Keyboard.GetState();

if (kbs.IsKeyDown(Keys.Left)) viewAngle2 -= 0.01f;

if (kbs.IsKeyDown(Keys.Right)) viewAngle2 += 0.01f;

if (kbs.IsKeyDown(Keys.Down)) viewAngle1 += 0.01f;

if (kbs.IsKeyDown(Keys.Up)) viewAngle1 -= 0.01f;

if (kbs.IsKeyDown(Keys.A)) viewDist -= 0.5f;

if (kbs.IsKeyDown(Keys.Z)) viewDist += 0.5f;

if (kbs.IsKeyDown(Keys.S)) balls[0].position.Z -= 0.05f;

if (kbs.IsKeyDown(Keys.X)) balls[0].position.Z += 0.05f;

viewAngle1 = MathHelper.Clamp(viewAngle1, MathHelper.PiOver2 + .1f, MathHelper.Pi - .01f);
viewDist = MathHelper.Clamp(viewDist, 5, 100);

UpdateBalls(gameTime);

base.Update(gameTime);
}

As a first simple simulation, I’m going to let the balls move around and bounce them of the cushions when they hit by reversing the velocity component perpendicular to the cushion. This is not an accurate simulation, since we would need to calculate the exact impact time to do this properly, but this is just a test. We use the gameTime parameter (passed to us by the XNA framework) to calculate a time duration value. We then loop through the balls and integrate the equation of motion – which means updating the position r = r + v * t. We also update the orientation by calculating the angle turned through as the distance travelled / the ball radius (d = r theta). This rotation is applied in the direction of motion. Later I’ll update this to reflect the more complex situation of the ball spinning in a direction not necessarily that of the velocity. This will bring about the effects of “side”, “backspin” and “follow”.


public void UpdateBalls(GameTime gameTime)
{
float t = (float)gameTime.ElapsedGameTime.Milliseconds / 1000f;

foreach (Ball ball in balls)
{
if (!ball.velocity.Equals(Vector3.Zero))
{
if (Math.Abs(ball.position.X) > tableWidth)
{
ball.velocity.X = -ball.velocity.X;
}

if (Math.Abs(ball.position.Z) > tableLength)
{
ball.velocity.Z = -ball.velocity.Z;
}

ball.position += Vector3.Multiply(ball.velocity, t);
ball.orientation = Quaternion.CreateFromAxisAngle(Vector3.Cross(Vector3.Normalize(ball.velocity), Vector3.Down),
Vector3.Distance(Vector3.Multiply(ball.velocity, t), Vector3.Zero) / Ball.ballRadius) * ball.orientation;
}
}
}

Nearly there, just need to define the Ball class. This is just really a struct at the moment, but later it will be doing some of the work when we add the physics.

class Ball
{
public static float ballRadius;
public static Model model;

public Texture2D texture;
public Vector3 position;
public Vector3 velocity;
public Quaternion orientation;
}



That's it. This is a screen shot of the result. The balls should roll around the table and bounce off the cushions (and the pockets!). You can adjust the camera angles

Followers