HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Linqy Sudoku game generator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linqygamesudokugenerator

Problem

I created a class that is able to generate a Sudoku board.

The following board generation steps are made:

Create a valid board with numbers on all squares, row by row

Basically I always generate the sequence 1 to 9 and I shift the elements on the cells. The shift amount depends on the row index.

Shuffle the board

Nothing extraordinary to explain here. Maybe just the fact that I also set the cells index here as well.

Empty the board until there is only 1 solution

Well, I am not totally sure if that is what my algorithm really does, but it seems to do a good job at least.

I start by picking the group with most visible cells (at the start they are all visible). Then, if I can solve that cell using sudoku solving methods (is this cell missing in the group/coulmn/row?) I make it invisible.

This ends when I am not able to find any other cell that I can hide.

```
public class SudokuGame
{
[DebuggerDisplay("{Value}")]
private class Cell
{
public int X { get; set; }
public int Y { get; set; }
public int Value { get; set; }
public bool IsVisible { get; set; }

private int Group
{
get { return Y/3 + X/3*3; }
}

public bool CanSolve(SudokuGame game)
{
var canSolve = game.GetColumnGroup(this)
.Where(c => c.X != X && c.Y != Y && c.Value == Value)
.All(c => c.IsVisible);

canSolve |= game.GetRowGroup(this)
.Where(c => c.X != X && c.Y != Y && c.Value == Value)
.All(c => c.IsVisible);

canSolve |= game.GetGroup(Group)
.Where(c => !c.IsVisible)
.Any(c =>
game.GetRow(c.X).Count(s => s.IsVisible) == 1 ||
game.GetColumn(c.Y).Count(s => s.IsVisible) == 1
);

return canSolve;
}
}

private Cell[][] _board = new Cell[9][];

public SudokuGame()
{
Contract.

Solution

There is one thing I don't like about the SudokuGame... it's a god-class doing everything which means it's doing too much.

I suggest refactoring the code so that the SudokuGame receives a SudokuBoard or some kind of a ISudokuBoardFactory. Then put everything sudoku-board releated into a SudokuBoard class that expects from you the size of the board etc.

Additionally I'd implemeted a ISudokuSolver that can check whether a game can be won.

I think it would also be a good idea to create another class that can only generate boards.

Put it all together and you have nice modular sudoku game where you can test each unit separately and validate its functionality.

Context

StackExchange Code Review Q#139448, answer score: 3

Revisions (0)

No revisions yet.