Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I'm trying to make a sudoku (http://www.sudoku.com) puzzle generator, but I've got some problems. After 1-2 or two rows he starts to generates rows that aren't valid in the end and the program gets stuck. Anyone got an idea on making a check for this that's still pretty fast?

The rules of the game are also explained below in the function for generating the puzzles.

 

[CS]

private void InitPuzzle()

{

//Rules:

//Each row must contain the digits 1-9

//And each square must contain the digits 1-9

//No duplicate values in a row or square

//thus applies: (x; x E 1-9 ; COUNT(x in Row && Square) = 1);

 

Random a = new Random();

int number = 0;

bool valid = false;

int[,] row = new int[1,9];//horizontal rows

int[,] vertrow = new int[9,1];//vertical rows

int[,] square = new int[3,3];//square

 

//x = rows

//y = colums

 

for(int x = 0; x < 3; x++)

{

for(int y = 0; y < 6; y++)

{

for(int rowx = 0; rowx < 9; rowx++)

row[0,rowx] = Convert.ToInt32(tiles[x,rowx].Text);

 

for(int rowy = 0; rowy < 9; rowy++)

vertrow[rowy,0] = Convert.ToInt32(tiles[rowy,y].Text);

 

if(y % 3 == 0)

{

for(int sqrx = 0; sqrx < 3; sqrx++)

for(int sqry = 0; sqry < 3; sqry++)

{

if(x % 2 == 0 && x != 0)

square[sqrx,sqry] = Convert.ToInt32(tiles[(x-2)+sqrx,y+sqry].Text);

if((x+1) % 2 == 0)

square[sqrx,sqry] = Convert.ToInt32(tiles[(x-1)+sqrx,y+sqry].Text);

if(x % 3 == 0)

square[sqrx,sqry] = Convert.ToInt32(tiles[x+sqrx,y+sqry].Text);

}

}

 

while(!valid)

{

number = a.Next(1,10);

 

//Number is not in this row

for(int rowx = 0; rowx < 9; rowx++)

{

if(number!=row[0,rowx])

valid=true;

else

{

valid=false;

rowx = 9;

}

}

 

//Number is not in this square

if(valid)

{

for(int sqrx = 0; sqrx < 3; sqrx++)

for(int sqry = 0; sqry < 3; sqry++)

{

if(number!=square[sqrx,sqry])

valid=true;

else

{

valid=false;

sqry = 3;

sqrx = 3;

}

}

}

 

//Number is not in this vertical row

if(valid)

{

for(int rowy = 0; rowy < 9; rowy++)

{

if(number!=vertrow[rowy,0])

valid=true;

else

{

valid=false;

rowy = 9;

}

}

}

 

//Then it's a valid number

if(valid)

tiles[x,y].Text = number.ToString();

}

 

valid = false;

 

}

 

valid = false;

}

 

}

[/CS]

For questions about VS .net extensibility, please fire at me! :)

For readability, please use the [ CS][/CS ] tags

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...