|
-
Jun 22nd, 2007, 03:35 AM
#1
[RESOLVED] a simple error? (creating sudoku grid)
I am writing a sudoku program from scratch in vb.net (which i just switched to).
I am having a fit of a time getting the grid to generate. Here's the code, which i don't even have all the number checks in place, and it still doesn't work.
Code:
Randomize()
Dim num As Integer, x As Integer, y As Integer, z As Integer, Unique As Boolean
ReDim SudokuGrid(9, 9) 'erases the current numbers
For y = 1 To 9
For x = 1 To 9
Do
Unique = True
num = Int(Rnd() * 9) + 1
'first compare to horizontal
For z = 1 To x
If z <> x Then If SudokuGrid(z, y) = num Then Unique = False : Exit For
Next
'then compare to vertical
If Unique = True Then
For z = 1 To y
If z <> y Then If SudokuGrid(x, z) = num Then Unique = False : Exit For
Next
End If
'then compare to others in this box
''place compare code here''
If Unique = True Then SudokuGrid(x, y) = num : Exit Do
Loop
Next
Next
'debug output
Dim debugoutput As String
For y = 1 To 9
For x = 1 To 9
debugoutput = debugoutput & Str(SudokuGrid(x, y))
Next
debugoutput = debugoutput + vbCrLf
Next
MsgBox(debugoutput)
End Sub
I highlighted in red the trouble spot. This code is supposed to generate a 9x9 grid of numbers. The check to see if horizontal is unique works fine. Every row has 1-9 inclusive in a random order.
But for whatever reason, it just won't work vertically. It gets stuck in a permanent loop. I've spent a few hours trying to figure out why. If no one can help, i'm going to try something different. but i sure would like to know what's wrong with this code.
-
Jun 22nd, 2007, 05:41 AM
#2
Re: a simple error? (creating sudoku grid)
Firstly I think choosing a number at random and then seeing if it fits is a very cpu intensive solution, secondly it's flawed because a number might fit fine but then preclude other numbers later...
Your code fills the rows then the columns starting in the top corner. It generates a random number and then checks each row, column (and then presumably block) for a repetition of your randomly chosen number ...
example
1 2 6 | 5 4 7 | 8 9 3
8 5 9 | 1 6 2 | 4 7 ?
In this example everything works fine until you reach the last square on the second row where there are no possible answers.
If you look at any decent Sudoku solvers and present it with a blank grid it should then fill it out for you.
-
Jun 22nd, 2007, 05:53 AM
#3
Re: a simple error? (creating sudoku grid)
Hi,
Here's thread about how to create a Sudoku generator:
http://www.vbforums.com/showthread.p...ghlight=sudoku
Hope it will help you,
sparrow1
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|