Sudoku Game

by Rob 16. May 2011 20:05

There's no shortage of Sudoku games, tutorials, and even source code, online....but I had a slow weekend and figured I'd take a stab at it.  One of these days, I'll rewrite it in F#.  Anyway - here's the core of it:

    Public Sub Solve()
        While SetObviousValues()            
        End While

        If IsSolved Then
            Print()
            Exit Sub
        End If

        Dim BestPoint As Point = GetLowestPossibleValuePoint()

        If BestPoint.X <> -1 Then
            Dim GuessVals() As Integer = GetPossibleValues(BestPoint.X, BestPoint.Y)

            If GuessVals.Count <> 0 Then
                For i As Integer = 0 To GuessVals.Count - 1                    
                    Dim newNumbers(,) As Integer = _Numbers.Clone
                    newNumbers(BestPoint.X, BestPoint.Y) = GuessVals(i)
                    Dim newGrid As New Grid(newNumbers)

                    newGrid.Solve()
                Next
            End If
        End If

    End Sub

This will find all possible solutions to a given puzzle.  Here's how'd you use it (as a console application)...

        Dim StartVal(,) As Integer = { _
                                    {0, 0, 0, 0, 0, 0, 0, 7, 6}, _
                                    {0, 0, 0, 0, 7, 8, 0, 0, 2}, _
                                    {8, 0, 0, 0, 4, 2, 3, 0, 0}, _
                                    {1, 0, 9, 0, 0, 0, 0, 0, 0}, _
                                    {0, 2, 0, 7, 8, 9, 0, 4, 0}, _
                                    {0, 0, 0, 0, 0, 0, 9, 0, 5}, _
                                    {0, 0, 2, 8, 6, 0, 0, 0, 7}, _
                                    {7, 0, 0, 2, 1, 0, 0, 0, 0}, _
                                    {4, 5, 0, 0, 0, 0, 0, 0, 0}}

        Dim myGrid As New Grid(StartVal)

        myGrid.Print()
        Console.Read()
        myGrid.Solve()

The source is available here.  

Or, you can play the online version here

Categories:

Comments (2) -

Gucci Outlet
Gucci Outlet People's Republic of China on 6/6/2011 6:41:29 PM

If a thing is worth doing it is worth doing well.

bill
bill United States on 10/20/2011 9:20:26 AM

such a great code.
thank you so much for providing such detailed information!

Pingbacks and trackbacks (2)+

Comments are closed