all groups > c# > february 2007 >
You're in the

c#

group:

for loop only runs when theres a breakpoint in it


for loop only runs when theres a breakpoint in it fletch
2/15/2007 9:48:22 PM
c#:
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?
Re: for loop only runs when theres a breakpoint in it PS
2/16/2007 12:00:00 AM

[quoted text, click to view]

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

[quoted text, click to view]

Re: for loop only runs when theres a breakpoint in it Morten Wennevik [C# MVP]
2/16/2007 12:00:00 AM
Hi Fletch,

I'm betting the problem is Random rand =3D 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 eac=
h =

turn the timestamp will not have time to change, effectively causing ran=
d =

to be seeded with the same number at each turn. You probably see only o=
ne =

cell get a number since x, y and r will get the same each time. When yo=
u =

use a breakpoint, you give the timestamp plenty of time to change, givin=
g =

you a new seed the next turn.

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

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

board[x, y] =3D r;
}


[quoted text, click to view]



-- =

Happy Coding!
Re: for loop only runs when theres a breakpoint in it Jon Skeet [C# MVP]
2/16/2007 12:00:00 AM
[quoted text, click to view]

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.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
AddThis Social Bookmark Button