This code is giving me a headache, to summarise my goal of my program is to generate complete sudoku boards that can be used in future for a game. I’m almost there I’ve got no repeating numbers in the smaller grids but I am still getting repeating numbers in the larger grid. Screenshot of my program displaying my issue:
A preface to my code:
- gameGrid is a 2d array of 9 arrays considing of 9 indexes each
- btnGrid is a mirror of gameGrid but is for the buttons in gui
- gridXX refers to each smaller 3×3 grid on the sudoku board
The rest of the code is explained programatically within the function, I believe the problem is within the “checkCol” and “checkRow” parts which are marked with comments.
Any help at all is greatly appreciated and thank you to any commenters in advanced!
Thanks,
Ben
Code:
private void generateBtn_Click(object sender, EventArgs e){
Random r = new Random();
//Row and Col max is one less as arrays start at 0
int rowMax = 9;
int colMax = 9;
for (int i = 0; i < rowMax; i++)
{
for (int j = 0; j < colMax; j++)
{
bool checking = false;
bool foundSame = false;
while (checking == false)
{
foundSame = false;
string num = r.Next(1, 10).ToString();
Debug.WriteLine(num);
//check row
for (int k = 0; k < rowMax; k++) {
if (gameGrid[i,k] == num) { foundSame = true; break; }
if (gameGrid[i,k] == "") { break; }
}
//check col
for (int k = 0; k < colMax; k++)
{
if (gameGrid[k,j] == num) { foundSame = true; break; }
}
//check square
if (grid00.Contains(btnGrid[i, j])) { foundSame = checkIfContains(grid00, num); }
if (grid10.Contains(btnGrid[i, j])) { foundSame = checkIfContains(grid10, num); }
if (grid20.Contains(btnGrid[i, j])) { foundSame = checkIfContains(grid20, num); }
if (grid01.Contains(btnGrid[i, j])) { foundSame = checkIfContains(grid01, num); }
if (grid11.Contains(btnGrid[i, j])) { foundSame = checkIfContains(grid11, num); }
if (grid21.Contains(btnGrid[i, j])) { foundSame = checkIfContains(grid21, num); }
if (grid02.Contains(btnGrid[i, j])) { foundSame = checkIfContains(grid02, num); }
if (grid12.Contains(btnGrid[i, j])) { foundSame = checkIfContains(grid12, num); }
if (grid22.Contains(btnGrid[i, j])) { foundSame = checkIfContains(grid22, num); }
if (foundSame == false)
{
checking = true;
gameGrid[i,j] = num;
btnGrid[i,j].Text = num;
}
}
}
}}