Sunday, February 3, 2008

Sudoku Part 4: Implementing A Generator


In our last segment (Defining The Generator Behavior) we looked at the specifications required to generate new Sudoku puzzles. It turned out that from a specification standpoint, there were not many expectations that we placed on the generator. We basically just want a solvable sudoku puzzle. We didn't much care how it worked, or what the puzzle looked like, so long as the result was uniquely solvable.

Algorithm

Today, we're going to create our very first sudoku solver using a similar technique as the one we used to actually solve the puzzle. We're going to develop what I call the RecursiveGenerator.

In order to generate our puzzle, we'll first fill all board pieces with a valid sudoku value. While we're filling in each piece we'll ensure that we never create an invalid board. Meaning that at no time will we have a board with duplicate row values, column values or region values. We'll utilize a recursive algorithm very similar to the RecurisveSolver we developed previously.

Now that we have a fully populated sudoku board with no duplicate row, column or region values, we'll start removing values from random pieces. In order to do this we'll create a list of all pieces on the board and then assign a random double value to them and sort the list. We'll iterate over the list removing that piece's value from our board until our ISolver implementation reports that our board is an invalid puzzle. At this time we'll put back the last piece we removed and consider the puzzle generated.

Test Class Implementation

Our test class to test our generator implementation is only minimally more complex than the solver implementation we used in an earlier section. Because this generator we built has a dependency on an ISolver we need to provide an implementation which we have already tested so that our generator can operate successfully. For this we're obviously going to use our already tested RecursiveSolver implementation. Note that while it would be possible to use a different type of solver (or notably a mock solver), doing this would most likely require significant changes to the tests which we are running, and this is not an exercise we're yet willing to go through.


[TestClass]
public class When_RecursiveGenerator_Generates_A_Puzzle : When_A_New_Puzzle_Is_Generated
{
public When_RecursiveGenerator_Generates_A_Puzzle()
: base(new RecusiveGenerator(new RecursiveSolver()))
{

}
}


Notice that the only new twist to this code is that our constructor for RecursiveGenerator must now takes an implementation of ISolver.

RecursiveGenerator Source


public class RecusiveGenerator : IGenerator
{
private Random rand;
private ISolver solver;

public RecusiveGenerator(ISolver solver)
{
rand = new Random();
this.solver = solver;
}

public Puzzle Generate()
{
Puzzle puzzle = new Puzzle();

//fully fill a puzzle with valid pieces
GeneratePiece(GetMinimumPosibilityPiece(puzzle), puzzle);

//now remove random values until the puzzle is no longer
//uniquely solvable.


SortedList<double, Piece> sortedPieces = new SortedList<double, Piece>();
foreach (Piece piece in puzzle.Pieces)
{
sortedPieces.Add(rand.NextDouble(), piece);
}

Piece lastPiece = null;
Value? lastValue = null;

try
{
foreach (double key in sortedPieces.Keys)
{
lastPiece = sortedPieces[key];
lastValue = lastPiece.AssignedValue;
lastPiece.AssignedValue = null;
solver.Solve(puzzle);
}
}
catch (DuplicateSolutionFoundException)
{
//when we reach the point of a duplicate solution
//we need to put the last value we stripped off back.

lastPiece.AssignedValue = lastValue;
}

return puzzle;
}

private bool GeneratePiece(Piece piece, Puzzle puzzle)
{
if (piece == null)
{
return true;
}

HashSet<Value> potentials = CalculatePotentials(piece);

do
{
piece.AssignedValue = null;

// if there are no potential values for this piece then
// we have reached the end of the line.

if (potentials.Count == 0)
{
return false;
}

piece.AssignedValue = potentials.PopRandomItem();
} while (!GeneratePiece(GetMinimumPosibilityPiece(puzzle), puzzle));

return true;
}

private Piece GetMinimumPosibilityPiece(Puzzle puzzle)
{
Piece minimumPiece = null;
int minimumPossiblities = Enum.GetValues(typeof(Value)).Length + 1;

foreach (Piece piece in puzzle.Pieces)
{
int possibilities = CalculatePotentials(piece).Count;
if (!piece.AssignedValue.HasValue && possibilities < minimumPossiblities)
{
minimumPossiblities = possibilities;
minimumPiece = piece;
}
}

return minimumPiece;
}

private HashSet<Value> CalculatePotentials(Piece piece)
{
HashSet<Value> potentials = GetPossibleValues();

potentials.IntersectWith(GetSolutionValues(piece.Column));
potentials.IntersectWith(GetSolutionValues(piece.Row));
potentials.IntersectWith(GetSolutionValues(piece.Region));

return potentials;
}

private HashSet<Value> GetSolutionValues(IEnumerable<Piece> pieces)
{
HashSet<Value> values = GetPossibleValues();
foreach (Piece piece in pieces)
{
if (piece.AssignedValue != null)
{
values.Remove(piece.AssignedValue.Value);
}
}

return values;
}

private HashSet<Value> GetPossibleValues()
{
HashSet<Value> values = new HashSet<Value>();
foreach (Value val in Enum.GetValues(typeof(Value)))
{
values.Add(val);
}
return values;
}
}


Notice that a lot of this code is very similar to that of the solver. This could probably be refactored, but for now we'll leave as is.

Again, what do we have to show for our hard word? Our green lights of course!

Notes

For those readers with a keen eye, something may seem less than optimal regarding the approaches we took here in this section. We'll get in to what those may be and what we can do about them in future segments after we have built a UI to be able to show these generated Sudoku puzzles.

Sunday, January 27, 2008

Sudoku Part 3: Defining The Generator Behavior


In part 1 (Defining The Solver Behavior) we examined how Behavior Driven Development could assist us in defining the specifications of a small portion of our application. Today we're going to take the same approach, but instead we're going to tackle the Generation portion of a Sudoku puzzle instead of the solving of the puzzle.

We're going to resume our conversations with our domain expert, and see what types of behaviors this new piece of functionality should include.

Needed Behavior

Just like last time, we'll have simple questions and simple answers which will later drive how we create and define our behavior based unit tests.

  • What is the result when a new puzzle is generated?
    • No column should have duplicate values
    • No row should have duplicate values
    • No region should have duplicate values
    • The puzzle should be uniquely solvable.
Really, that's it. We don't care too much about how the puzzle is generated, or what it looks like (at least at this point), so long as the puzzle itself can be solved.

Notice, that making the puzzle solvable would actually be quite a tricky requirement if we had not already built a Sudoku solver in part 2 (Implementing A Solver). Lucky for us, since we have a fully tested solver which we have proven works we can plug that implementation in to our behavior tests for the generator in order to verify the output. Note that really any implementation of an ISolver will suffice for our purposes, since our behavior tests are actually written against the interface and not any particular implementation.

The BDD Style Specifications

We're going to write our test class (or specification) in much the same way we did before. We try to match the discussion with the domain expert as close as we can, and then write relatively simple tests which we can use to ensure our implementations provide the correct behavior.


[TestClass]
public abstract class When_A_New_Puzzle_Is_Generated
{
protected Puzzle puzzle;
private IGenerator generator;
private ISolver solver;

protected When_A_New_Puzzle_Is_Generated(IGenerator generator)
{
this.generator = generator;
this.solver = new RecursiveSolver();
}

[TestInitialize]
public void Initialize()
{
puzzle = generator.Generate();
}

[TestMethod]
public void No_Column_Should_Have_Duplicate_Values()
{
foreach (Column col in puzzle.Columns)
{
List<Value> foundValues = new List<Value>();
foreach (Piece piece in col)
{
if (piece.AssignedValue.HasValue)
{
Assert.IsFalse(foundValues.Contains(piece.AssignedValue.Value));
foundValues.Add(piece.AssignedValue.Value);
}
}
}
}

[TestMethod]
public void No_Row_Should_Have_Duplicate_Values()
{
foreach (Row row in puzzle.Rows)
{
List<Value> foundValues = new List<Value>();
foreach (Piece piece in row)
{
if (piece.AssignedValue.HasValue)
{
Assert.IsFalse(foundValues.Contains(piece.AssignedValue.Value));
foundValues.Add(piece.AssignedValue.Value);
}
}
}
}

[TestMethod]
public void No_Region_Should_Have_Duplicate_Values()
{
foreach (Region region in puzzle.Regions)
{
List<Value> foundValues = new List<Value>();
foreach (Piece piece in region)
{
if (piece.AssignedValue.HasValue)
{
Assert.IsFalse(foundValues.Contains(piece.AssignedValue.Value));
foundValues.Add(piece.AssignedValue.Value);
}
}
}
}

[TestMethod]
public void The_Puzzle_Should_Be_Uniquely_Solvable()
{
Assert.IsNotNull(solver.Solve(puzzle));
}
}

Tuesday, January 15, 2008

Sudoku Part 2: Implementing A Solver


In the previous posting (Defining The Solver Behavior) we discussed the needed behavior in order to build a working Sudoku solver. Today we're going to build our first implementation of a solver which exhibits the previously described behaviors.

Algorithm

For the first solver I took a relatively simple approach. It's not quite a brute-force solver, but it is close. I call the first implementation the RecursiveSolver, since it solves the puzzle using a recursive algorithm.

In order to solve the puzzle we'll first analyze the board position to determine the number of candidate values for each puzzle piece. The set of candiate values will be the full list of values minus the set of values in the piece's row, minus the set of values in the piece's column and then minus the set of values in the piece's region.

Once we have computed the candidate values for each piece, we'll record the piece with the fewest candidate values. We'll then loop over the candidate values in a random order calculating the piece with the minimum candidates given that move and continuing the process.

If we find a board position where there are no longer any pieces without an assigned value we know we have found a solution. If we have already recorded a value solution and we find a second board position we know we have found an invalid position.

If we found a board position where there is a piece with 0 potential values, we know we have traversed a path which will not lead to a solution.

If we traverse all possible paths of the puzzle and can not find a solution, then we know we have an unsolvable puzzle as our algorithm would have examined every possible choice a solver could make.

Broken into steps our algorithm looks like the following:
  1. Find The Piece With The Minimum Number Of Candidate Values
  2. If A Piece Is Found With No Candidate Values, Return Without Solution
  3. If No Pieces exist with Candidate Values Return the Solution We Are Done
  4. Loop Over Each Candidate Value
  5. Assign the Value to the Solution
  6. Return To Step 1 Given The New State
  7. If We Found A Solution, Verify That We Have Not Previously Found A Solution
  8. Loop To Step 4 Until No Other Candidates Are Available
  9. Return The Solution If It Was Found
Test Class Implementations

In the last installment we created abstract behavior tests since we did not have a specific implementation of a solver. We had a set of behaviors we wanted all potential solver implementations to exhibit. So first we need to create concrete test classes which inherit from our abstract ones.

First, let's look at what we need to do for the case when a puzzle is solved:


[TestClass]
public class When_RecursiveSolver_Solves_A_Puzzle : When_A_Puzzle_Is_Solved
{
public When_RecursiveSolver_Solves_A_Puzzle()
: base(new RecursiveSolver())
{

}
}


That's pretty simple isn't it? Now, this works fine with the MSTest tool, I have not actually verified that this technique works in other .NET unit testing frameworks, but I believe it does. We rely on inheritance to pull all of our expectations from our base test class.

We can continue this pattern for all other behavior cases as well. Take special note to the fact that we are constructing the instance of the solver we want to test in the constructor of the test class. This is needed since our base class takes an ISolver to use for its test cases.

Solver Source

Now let's look at the good stuff. What does the solver code look like?


public class RecursiveSolver : ISolver
{
private Random rand;

public RecursiveSolver()
{
this.rand = new Random();
}

#region ISolver Members

public Solution Solve(Puzzle puzzle)
{
Solution solution = new Solution(puzzle);

solution = SolvePiece(FindMinimumCandidatePiece(solution), solution);

return solution;
}

#endregion

private Solution SolvePiece(Piece piece, Solution solution)
{
//when the provided piece is null we know there are no remaining
//pieces to be filled in indicating that the puzzle is solved.

if (piece == null)
{
return solution;
}

//we clone the current solution to ensure that we always provide
//later steps with the same configuration. Otherwise once the item
//recursed the values within the soultion reference would have changed.

solution = (Solution)solution.Clone();
Solution returnSolution = null;
Solution foundSolution = null;
HashSet<Value&*gt; candidates = CalculateCandidates(piece, solution);

//loop over all possible choices for this piece. If we finish
//looping and no slution was found the earlier steps will have
//a null solution indicating the path was incorrect.

while (candidates.Count > 0)
{
solution.Values[piece] = candidates.PopRandomItem();
returnSolution = SolvePiece(FindMinimumCandidatePiece(solution), solution);

if (returnSolution != null)
{
if (foundSolution != null)
{
throw new DuplicateSolutionFoundException("Provided puzzle is invalid.");
}
foundSolution = returnSolution;
}
}

return foundSolution;
}

private Piece FindMinimumCandidatePiece(Solution solution)
{
Piece foundPiece = null;
int minimumCandidates = 10;

foreach (Piece piece in solution.Puzzle.Pieces)
{
if (!solution.Values.ContainsKey(piece))
{
HashSet<Value> candidates = CalculateCandidates(piece, solution);
if (candidates.Count < minimumcandidates)
{
minimumCandidates = candidates.Count;
foundpiece = piece;

//If we found a piece with only 1 candidate we can stop looking
//since 1 is the minimum possible candidates for a valid piece.

if (minimumCandidates == 1)
{
break;
}
}
}
}

return foundPiece;
}

private HashSet<Value> CalculateCandidates(Piece piece, Solution solution)
{
HashSet<Value> candidates = new HashSet<Value>((Value[])Enum.GetValues(typeof(Value)));

candidates.ExceptWith(GetAssignedValues(piece.Column, solution));
candidates.ExceptWith(GetAssignedValues(piece.Row, solution));
candidates.ExceptWith(GetAssignedValues(piece.Region, solution));

return candidates;
}

private HashSet<Value> GetAssignedValues(IEnumerable<Piece> pieces, Solution solution)
{
HashSet<Value> values = new HashSet<Value>();

foreach (Piece piece in pieces)
{
if (solution.Values.ContainsKey(piece))
{
values.Add(solution.Values[piece]);
}
}

return values;
}
}


Notice that there is actually a lot of logic within this solver. While it could be argued that some of this logic deserves its own behavior class, at this time I'm going to consider it premature optimization, and leave it for future refactoring.

For example the ability to calculate potential values isn't something which is specific to a solver, or at least this solver. This could be usable elsewhere. If/When it becomes valuable to break it out we'll do it.

Also of note is the PopRandomValue method on the HashSet<>. PopRandomValue is obviously an extension method here, just don't tell anyone! This method randomly selects an item from the Set and then removes it from the set so it won't be selected next time. The implementation is as follows:


public static class HashSetExtension
{
private static Random rand;

static HashSetExtension()
{
rand = new Random();
}

public static T PopRandomItem(this HashSet<T> set)
{
List<T> list = new List<T>(set);
T item = list[rand.Next(0, list.Count - 1)];
set.Remove(item);
return item;
}
}


What do we have to show for all of our effort? Well a pretty screen with lots of green of course!



Notes

Note that we could have included additional behavior tests regarding how this particular solver should behave. At this time I don't deem it necessary since our only real requirements is that the solver gives valid solutions when one is available, and reports when no solution is available.

As previously mentioned we could break apart some items of this solver into multiple solvers. We'll investigate those possibilities at a later point.

Look for the next section where we'll discuss our Sudoku puzzle generator!

-- John Chapman

Saturday, January 5, 2008

Sudoku Part 1: Defining The Solver Behavior


In the introduction I talked briefly about my goals for this series. I wanted to create both a Sudoku generator which could generate puzzles for both myself and a theoretical automatic solver. There are many places to find such tools on the internet, but my goal was to use this as an exercise to show how someone could use various techniques and tools such as Behavior-Driven Development and the Castle Windsor Project. Today, we'll start with Behavior-Driven Development.

Needed Behavior

What are we trying to accomplish Here? Let's start with the Sudoku Solver first. Let's pretend that I am having a conversation with a customer who is asking me to write this Sudoku solver for them. Let's also say that I am not familiar with sudoku puzzles. First the customer explains to me that a Sudoku puzzle is a 9x9 grid with 9 3x3 sub-regions within the grid where each cell can hold a value from 1-9. He also explains that the puzzle begins with some of the cells (or pieces) already filled in for us, and the rest is for the solver to fill in.

So we have the following dialog:

  • What happens when the puzzle is solved?
    • All cells should be assigned a value.
    • No column should have duplicate values.
    • No row should have duplicate values.
    • No region should have duplicate values.
The customer explains to me that if the solution meets the provided criteria we are guaranteed of a valid solution for the given puzzle. But then I start thinking. Is it possible to be given a Sudoku puzzle which has many possible solutions? I think that if I don't place any pieces, clearly there would be many possible solutions. So this leads to the following:
  • What happens when a puzzle has multiple solutions?
    • The puzzle should be reported as invalid.
Ok, so now I know what happens if a puzzle has many solutions, but what if the puzzle has no solution.
  • What happens when a puzzle has no solution?
    • There is no solution for the puzzle.
Ok, so my customer gave me a pretty weird look on that one, but there is nothing wrong with asking right?

Note that my customer has not told me any specifics about how he or she would like the puzzle to be solved, only that the puzzle should be solved and what the result of a valid solved puzzle would be.

Letting The Behavior Drive Our Development

Ok, so now I'm back in the office, ready to begin work on the Sudoku solver for my customer. Where do I begin? This is where the Behavior-Driven Development (BDD) comes in to play. Behavior-Driven Development is basically a Test-Driven Development (TDD) technique where your tests are designed around the needed behaviors of your software. This should result in tests which are far easier to refactor, since most changes results in complete removal or replacement of tests instead of removing pieces of a method based test.

Additionally by wording your tests in such a way that it portrays the resulting behavior of the software, the results of the tests become easy for our customers to read to understand how the software is working.

Let's look at the resulting unit tests to show what I'm talking about. First lets look at solving a valid puzzle. (*Warning* These tests are currently written in MSTest, I will most likely change to NUnit or mbUnit before releasing the entire source code.)


[TestClass]
public abstract class When_A_Puzzle_Is_Solved
{
private Sudoku.Solver.ISolver solver;
private Puzzle puzzle;
private Solution solution;

public When_A_Puzzle_Is_Solved(Sudoku.Solver.ISolver solver)
{
this.solver = solver;
}

[TestInitialize]
public void Initialize()
{
CreateSolvablePuzzle();
solution = solver.Solve(puzzle);
}

private void CreateSolvablePuzzle()
{
puzzle = new Puzzle();

puzzle.Rows[0][1].AssignedValue = Value.Five;
puzzle.Rows[0][2].AssignedValue = Value.Four;
puzzle.Rows[0][7].AssignedValue = Value.Two;
puzzle.Rows[1][0].AssignedValue = Value.Three;
puzzle.Rows[1][3].AssignedValue = Value.Four;
puzzle.Rows[2][0].AssignedValue = Value.Seven;
puzzle.Rows[2][3].AssignedValue = Value.Eight;
puzzle.Rows[2][6].AssignedValue = Value.Three;
puzzle.Rows[2][7].AssignedValue = Value.Five;
puzzle.Rows[3][1].AssignedValue = Value.Seven;
puzzle.Rows[3][2].AssignedValue = Value.One;
puzzle.Rows[3][5].AssignedValue = Value.Five;
puzzle.Rows[3][8].AssignedValue = Value.Three;
puzzle.Rows[4][0].AssignedValue = Value.Six;
puzzle.Rows[4][3].AssignedValue = Value.Three;
puzzle.Rows[4][5].AssignedValue = Value.Eight;
puzzle.Rows[4][8].AssignedValue = Value.Nine;
puzzle.Rows[5][0].AssignedValue = Value.Five;
puzzle.Rows[5][3].AssignedValue = Value.Nine;
puzzle.Rows[5][6].AssignedValue = Value.Four;
puzzle.Rows[5][7].AssignedValue = Value.Seven;
puzzle.Rows[6][1].AssignedValue = Value.Eight;
puzzle.Rows[6][2].AssignedValue = Value.Five;
puzzle.Rows[6][5].AssignedValue = Value.Four;
puzzle.Rows[6][8].AssignedValue = Value.One;
puzzle.Rows[7][5].AssignedValue = Value.Three;
puzzle.Rows[7][8].AssignedValue = Value.Six;
puzzle.Rows[8][1].AssignedValue = Value.Six;
puzzle.Rows[8][6].AssignedValue = Value.Eight;
puzzle.Rows[8][7].AssignedValue = Value.Nine;
}

[TestMethod]
public void All_Pieces_Should_Have_A_Value()
{
foreach (Piece piece in puzzle.Pieces)
{
Assert.IsTrue(solution.Values.ContainsKey(piece));
}
}

[TestMethod]
public void No_Column_Should_Have_Duplicate_Values()
{
foreach (Column col in puzzle.Columns)
{
List<Value> foundValues = new List<Value>();
foreach (Piece piece in col)
{
Assert.IsFalse(foundValues.Contains(solution.Values[piece]));
foundValues.Add(solution.Values[piece]);
}
}
}

[TestMethod]
public void No_Row_Should_Have_Duplicate_Values()
{
foreach (Row row in puzzle.Rows)
{
List<Value> foundValues = new List<Value>();
foreach (Piece piece in row)
{
Assert.IsFalse(foundValues.Contains(solution.Values[piece]));
foundValues.Add(solution.Values[piece]);
}
}
}

[TestMethod]
public void No_Region_Should_Have_Duplicate_Values()
{
foreach (Region region in puzzle.Regions)
{
List<Value> foundValues = new List<Value>();
foreach (Piece piece in region)
{
Assert.IsFalse(foundValues.Contains(solution.Values[piece]));
foundValues.Add(solution.Values[piece]);
}
}
}
}



Notice how closely these tests match the above dialog I had with the fictional customer. Anyone, including the customer should be able to read that test fixture (especially how it formatted in a proper runner) and verify that the behavior is correct. Plus, the test methods themselves are very short, easy to read and verify.

Behavior-Driven Development works by you first defining the scenario. The scenario becomes the test class itself with the test initialization being the place where we place our objects in to the appropriate state for our scenario. Each method then becomes a validation of what happens in a given scenario. The methods and class names are then written out as words so it easy to tell what behaviors are being tested.

Note that the initialization logic of this test builds a valid Sudoku puzzle and then asks the solver to solve it. As proof of a valid solution I have provided the puzzle and the associated solution in red below.


There are a few things which need to be explained in this code.

First, I chose to use an enumeration for puzzle values as a way to limit the values of the puzzle. This actually looks very lame when I read it, having the names of numbers represent the numbers themselves, and it may be refactored at a later point, but for now it helped me ensure no 0s or 10s showed up (although I have learned that enumerations are pretty lame and nothing stops you from assigning an invalid integer value to the enumeration, but that's a post for another day).

Second, notice that I used an interface for my solver, not a specific solver. The reason for this is really simple. I don't know at this point how the puzzle will be solved, only what the result of a solver should be. It doesn't matter how the internal solver works at this point, provided it sticks to the interface and this root behavior.

I also made the choice to make the Puzzle class and a separate Solution class. Basically this just allows a puzzle to remain free of solution information and would theoretically allow someone to make Puzzle classes persistable and not have to worry about updating a puzzle while creating a solution for it.

Now that we have our behaviors defined for what happens with a valid puzzle, lets move on to the other cases which were discussed in the dialog with the customer.


[TestClass]
public abstract class When_A_Puzzle_Has_Multiple_Solutions
{
private ISolver solver;
private Puzzle puzzle;

public When_A_Puzzle_Has_Multiple_Solutions(ISolver solver)
{
this.solver = solver;
}

[TestInitialize]
public void Initialize()
{
CreateInvalidPuzzle();
}

private void CreateInvalidPuzzle()
{
puzzle = new Puzzle();

puzzle.Rows[4][4].AssignedValue = Value.Five;
}

[TestMethod]
[ExpectedException(typeof(DuplicateSolutionFoundException))]
public void The_Solver_Should_Report_An_Invalid_Puzzle()
{
solver.Solve(puzzle);
}
}


Note that in this scenario, many valid sudoku boards could be created when only one piece is filled in. As such we are saying that whenever a puzzle with many solutions is provided we expect any solver to throw an exception.

I'm not actually a big fan of this approach, but I did it anyways here. Basically checking for duplicate solutions is something which I think would actually be useful for business logic. Therefore I for see cases where I could wind up using this exception for flow control, which I am opposed to. However, since at this point I just need a failure it works fine, and I can always refactor it later.

There is still one case remaining from the solver discussion:



[TestClass]
public abstract class When_A_Puzzle_Has_No_Solution
{
private Puzzle puzzle;
private ISolver solver;

public When_A_Puzzle_Has_No_Solution(ISolver solver)
{
this.solver = solver;
}

[TestInitialize]
public void Initialize()
{
puzzle = new Puzzle();

puzzle.Rows[0][0].AssignedValue = Value.Five;
puzzle.Rows[0][1].AssignedValue = Value.One;
puzzle.Rows[0][2].AssignedValue = Value.Three;
puzzle.Rows[0][3].AssignedValue = Value.Two;
puzzle.Rows[0][4].AssignedValue = Value.Nine;
puzzle.Rows[0][5].AssignedValue = Value.Four;
puzzle.Rows[0][6].AssignedValue = Value.Eight;
puzzle.Rows[0][7].AssignedValue = Value.Seven;
puzzle.Rows[0][8].AssignedValue = Value.Six;
puzzle.Rows[1][0].AssignedValue = Value.Eight;
puzzle.Rows[1][1].AssignedValue = Value.Two;
puzzle.Rows[1][2].AssignedValue = Value.Seven;
puzzle.Rows[1][3].AssignedValue = Value.Five;
puzzle.Rows[1][4].AssignedValue = Value.Six;
puzzle.Rows[1][5].AssignedValue = Value.One;
puzzle.Rows[1][6].AssignedValue = Value.Three;
puzzle.Rows[1][7].AssignedValue = Value.Four;
puzzle.Rows[1][8].AssignedValue = Value.Nine;
puzzle.Rows[2][0].AssignedValue = Value.Nine;
puzzle.Rows[2][1].AssignedValue = Value.Six;
puzzle.Rows[2][2].AssignedValue = Value.Four;
puzzle.Rows[2][3].AssignedValue = Value.Seven;
puzzle.Rows[2][4].AssignedValue = Value.Eight;
puzzle.Rows[2][5].AssignedValue = Value.Three;
puzzle.Rows[2][6].AssignedValue = Value.One;
puzzle.Rows[2][7].AssignedValue = Value.Two;
puzzle.Rows[2][8].AssignedValue = Value.Five;
puzzle.Rows[3][0].AssignedValue = Value.Six;
puzzle.Rows[3][1].AssignedValue = Value.Five;
puzzle.Rows[3][2].AssignedValue = Value.One;
puzzle.Rows[3][3].AssignedValue = Value.Three;
puzzle.Rows[3][4].AssignedValue = Value.Seven;
puzzle.Rows[3][5].AssignedValue = Value.Nine;
puzzle.Rows[3][6].AssignedValue = Value.Two;
puzzle.Rows[3][7].AssignedValue = Value.Eight;
puzzle.Rows[3][8].AssignedValue = Value.Four;
puzzle.Rows[4][0].AssignedValue = Value.Two;
puzzle.Rows[4][1].AssignedValue = Value.Eight;
puzzle.Rows[4][2].AssignedValue = Value.Nine;
puzzle.Rows[4][3].AssignedValue = Value.One;
puzzle.Rows[4][4].AssignedValue = Value.Five;
puzzle.Rows[4][5].AssignedValue = Value.Six;
puzzle.Rows[4][6].AssignedValue = Value.Seven;
puzzle.Rows[4][7].AssignedValue = Value.Three;
}

[TestMethod]
public void No_Solution_Should_Be_Provided()
{
Assert.IsNull(solver.Solve(puzzle));
}
}


Note that for this scenario I took the puzzle from Part 0 which proved to be unsolvable and used it as my test puzzle.

Hopefully this gives you a good idea of how to define your behaviors. In the next post we'll look at creating concrete tests for an actual implementation of a solver that exhibits the behaviors we discussed here. Note that we discussed the behavior unit tests first since when developing with Behavior-Driven Development, the behavior tests come first!

--John Chapman

Wednesday, January 2, 2008

CodeMash 2008 Here I Come!



Well, it's official I've gone and registered for CodeMash 2008! I'm really looking forward to this conference. If anyone who reads this is going to attend let me know, maybe we can meet up at some point.

These are just some of the interesting topics I'm looking forward to.

  1. LinqTo: Implementing IQueryProvider (Bill Wagner)
    • Has anyone out there taken a look at what it takes to implement your own Linq provider? It's a major pain in the rear! Now, I don't know to what depths Bill will go, but any good overview would really be helpful. For this session I'm not really looking for a good how to implement guide, since I doubt I'll ever work on my own custom Linq provider, but really it's more to help me get a better grasp of how Linq is working under the covers to help myself in consuming it!
  2. Putting the Fun into Functional with F# (Dustin Campbell)
    • Ok, so I've kind of been watching the boat sail on all of the popular dynamic languages. I've dabbled in the past with python, but only very slightly. I've written a modest amount of javascript to get the hang of the ideas behind it, but I think a good solid introduction to the up and coming dynamic first class citizen of .NET is in order. Let's get a good introduction to all of the fuss. I should have enough of python to follow along with the presentation. Again, this isn't something I plan to use on a day to day basis, but rather just help me understand how the other half lives, and help me to understand why I make the choices that I do.
  3. Introduction To Behavior Driven Development (Andrew Glober)
    • This one concerns me a little bit with the introduction tag, but I'm starting to become a big fan of Behavior Driven Development or (BDD). Any additional insight in to the thought processes which it takes to implement it properly would be beneficial to me. Plus the fact that it is being shown for a Java implementation might help me to think a little bit out of the box while implementing BDD myself in the C# world.
  4. Story-Driven Testing (Jim Holmes)
    • This one basically belongs with the prior item. It's just an area which I want to learn more about. I believe this one should have a .NET focus (not that it is even necessarily for the topic).
  5. Introducing Castle (Jay R. Wren)
    • Castle is one of those projects I've grown to enjoy. I still won't use some parts of the project (like ActiveRecord), but that is also the beauty of Castle. You don't have to. You take the pieces you want. I've grown to enjoy Microkernel/Windsor and while I've never actually used MonoRail, it actually makes a lot of sense to me. The Microsoft MVC framework actually helped me realize just how good of an MVC framework already existed for the .NET platform. So, while the term Introducing may be a slight put off, there is still a chance to see some items in a different light. Plus, I've met Jay in the past, and he's a sharp guy. I would like to see a full presentation on what he has to say about the subject.
  6. Introduction To Workflow Foundation (Keith Elder)
    • On this one I don't really mind the Introduction part. I really don't know much about implementing WF. I understand you need to run the engine yourself, and I've seen the GUI used to create workflows, but really I don't know much beyond that. It's something which has seemed like it would provide benefits to me and my projects in the past, but I haven't ever gotten enough expertise to know for sure if it was something to invest in or not. Hopefully this will help me down that path.
  7. Rails: A Peek Under The Covers (Brian Sam-Bodden)
    • I'm going a bit in to the deep end on this one. I understand only the absolute minimum of Ruby, yet who hasn't heard of Ruby on Rails? This may give a better oversight regarding why it has become such a popular framework. I'm familiar with the ideas behind what the Rail framework offers, but seeing how it works with Ruby should be interesting.
And this is just a short list. I haven't actually checked to see what the times are for these sessions, lets just hope I am able to get to all of them.

Hopefully I'll see you all at CodeMash!

--John Chapman

Sunday, December 30, 2007

Sudoku Part 0: Introduction


It's been a while since my last post here. Part of the reason it has been so long is the fact that I traveled for the holidays, making it more difficult to make time to update this blog.

While traveling I break out sudoku (and other similar puzzle games) to help the time go by on the way to my destination. As a programmer I tend to take any problem I'm solving and analyze it as if I was developing a program to solve the problem for me. This isn't generally something I follow through on, but rather just a mental exercise where I wonder about the what ifs.

While working on a Sudoku puzzle I thought, as fun as solving this puzzle is, writing an algorithm that solved it in the same manner that I do would be even more enjoyable. Better yet, there may be many ways to build a sudoku solving algorithm. I also thought that in order to make an enjoyable sudoku solving algorithm I would also need to create a sudoku generating algorithm. Again, I thought there may be potential for many algorithms.

This time it got me thinking. Sudoku is fun, maybe this would be a good platform to introduce some topics. I have spent some time reading about Behavior-Driven Development (BDD), and would like to introduce an example of it on my blog. This seems like a good candidate. Most people are familiar with the puzzles. Secondly, I would also like to use this as an example for how to use a Dependency Injection framework. The fact that I hope to be able to generate multiple algorithms would seem to enforce the use of such a tool here.

I plan to make this a multi-part series as there are too many topics to cover to justify a single blog post. I am currently investigating this program now, so don't blame me if it takes a while to write the entire series.

Initial Thoughts

When I was first thinking about these problems on the Plane I thought a sudoku generator would be relatively simple. Well I can now say with confidence that it is not. The algorithm I formed in my head went something like the following:
  1. Divide the board in to rows, columns and regions, matching the general rules for the game.
  2. For each row, column and region create a set of Sudoku values (1-9) which are valid to be used for that grouping.
  3. Loop over all pieces of the board
  4. For each piece take the intersection of the valid values from this pieces row, column and region
  5. Randomly select a value from the remaining values, assign it's value to the piece and then remove it from the list of valid values for the pieces row, column and region.
  6. Once a valid board is created, randomly select a piece on the board to clear the value from
  7. Continue randomly removing values until the puzzle is no longer uniquely solvable, and re-add the last removed value.
This seemed like a reasonable algorithm to me. It seemed that there would always be a choice for valid values seeing as all previous pieces used valid values. I guess I just assumed that while placing pieces there would always be remaining valid pieces until you finished the puzzle. To my initial surprise, this algorithm failed on step 5 every time. The generator kept kitting situations where there were no valid values which could be placed on the current piece.

See the below example of the result of my algorithm. Note that there is no valid value which can be placed in the next box, even though all previous entries were entirely valid. According to the row of the piece the value should be 4. Yet 4 is invalid for that piece's column and region. So clearly 4 will not work there. Any value besides 4 will cause an issue for the row. This algorithm clearly doesn't work.


With that experiment I'm pretty much back to the drawing board. I do have a few ideas on algorithms that should work, but my goal with this is to have at least two working sudoku generation algorithms. So far I'm at least enjoying the hunt for a working algorithm. I would like to create at least one solution on my own, but at some point I may have to break down and look for some assistance.

--John Chapman

Sunday, December 16, 2007

UI: Good Use For Extension Methods

Ok, this is a little weird for me, but I think I just had my epiphany. I think I have finally converted in to an Extnsions Methods believer! I know, first there was C# 3.0 Extension Methods? A Good Idea? and then there was Reserving Judgement, but now I have found where I really, really like them.

How many of you have written a class like this:


public class Person
{
private string firstName;
private string lastName;

public string FirstName
{
get { return firstName; }
set { firstName = value; }
}

public string LastName
{
get { return lastName; }
set { lastName = value; }
}

public string GetFullName()
{
return LastName + ", " + FirstName;
}
}


I don't know about you, but I feel dirty every time I write something like that. To me this is display logic, and now it's polluting my business objects! This really smells to me. This smells so bad that I prefer to put a method on my page which does the formatting for me. But the problem is that people are used to this sort of syntax. They expect this to be how they format that class.

How do we satisfy both sides? Keep the presentation logic out of the business layer, yet keep the interfaces clean? Enter Extension Methods!

In order to solve this problem I would now create a new static class in my web assembly (UIHelper possibly, or another name that fits). This new class would look like the following:


public static class UIHelper
{
public static string GetFullName(this Person person)
{
return person.LastName + ", " + person.FirstName;
}
}


Now you can take the GetFullName method out of the Person class and use the extension method in your UI layer instead. The class will still work exactly the same way from a UI perspective, except when working within the Person there will no longer be a GetFullName method.

The Person class now looks like this:

public class Person
{
private string firstName;
private string lastName;

public string FirstName
{
get { return firstName; }
set { firstName = value; }
}

public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}


Just make sure you add the using directive to the namespace which contains the UIHelper class on your page (or add an Import directive to your aspx file). Your code on the page now looks like the following:

This is actually the happiest I've been with any use of extension methods when you control the class which is being extended.

--John Chapman

Blogger Syntax Highliter