for loop only runs when theres a breakpoint in it

  • Thread starter Thread starter fletch
  • Start date Start date
F

fletch

I'm trying to write a little sudoku game. When i try to set a board i
use a for loop.
Here it is
for (int c = 0; c < 6; c++)
{
Random rand = new Random();
int x = rand.Next(0, 9);
int y = rand.Next(0, 9);
int r = rand.Next(1, 9);

board[x, y] = r;

}
but for some reason it only runs once unless i put a break point
anywhere in it.
When there's a breakpoint in it it works fine though. Anyone got any
ideas to why?
 
fletch said:
I'm trying to write a little sudoku game. When i try to set a board i
use a for loop.
Here it is
for (int c = 0; c < 6; c++)
{
Random rand = new Random();
int x = rand.Next(0, 9);
int y = rand.Next(0, 9);
int r = rand.Next(1, 9);

board[x, y] = r;

}
but for some reason it only runs once unless i put a break point
anywhere in it.

How do you know it is only running once? What are you using as an indicator
of this? I see no counter or output that can be used to confirm that it only
runs once.

PS
 
Hi Fletch,

I'm betting the problem is Random rand = new Random(); It takes the
randomized seed from a timestamp, but if you use the same seed later you
will get the same sequence of numbers. Since you initialize rand at each
turn the timestamp will not have time to change, effectively causing rand
to be seeded with the same number at each turn. You probably see only one
cell get a number since x, y and r will get the same each time. When you
use a breakpoint, you give the timestamp plenty of time to change, giving
you a new seed the next turn.

Move the initialization of rand outside the loop to fix this.

Random rand = new Random();
for (int c = 0; c < 6; c++)
{
int x = rand.Next(0, 9);
int y = rand.Next(0, 9);
int r = rand.Next(1, 9);

board[x, y] = r;
}


I'm trying to write a little sudoku game. When i try to set a board i
use a for loop.
Here it is
for (int c = 0; c < 6; c++)
{
Random rand = new Random();
int x = rand.Next(0, 9);
int y = rand.Next(0, 9);
int r = rand.Next(1, 9);

board[x, y] = r;

}
but for some reason it only runs once unless i put a break point
anywhere in it.
When there's a breakpoint in it it works fine though. Anyone got any
ideas to why?
 
fletch said:
I'm trying to write a little sudoku game. When i try to set a board i
use a for loop.
Here it is
for (int c = 0; c < 6; c++)
{
Random rand = new Random();
int x = rand.Next(0, 9);
int y = rand.Next(0, 9);
int r = rand.Next(1, 9);

board[x, y] = r;

}
but for some reason it only runs once unless i put a break point
anywhere in it.
When there's a breakpoint in it it works fine though. Anyone got any
ideas to why?

It's running several times, but you're getting the same entries each
time.

See http://pobox.com/~skeet/csharp/miscutil/usage/staticrandom.html
for more information.
 
Back
Top