Random Numbers

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm hoping someone can help me with a problem I'm having using the random
class. I need to return a "random" number between 0 and 15, so i did this
Dim r as new Random()
Return r.Next(0, 15)

When I run my application, I call this code 12 times, one right after
another, but it keeps retuning the same number. If I put a break point in
and step through the application, the code runs correctly and I get
different numbers. Anyone heard of this before?

Any help would be greatly appreciated.

Chris
 
I'm hoping someone can help me with a problem I'm having using the random
class. I need to return a "random" number between 0 and 15, so i did this
Dim r as new Random()
Return r.Next(0, 15)

When I run my application, I call this code 12 times, one right after
another, but it keeps retuning the same number. If I put a break point in
and step through the application, the code runs correctly and I get
different numbers. Anyone heard of this before?

You want to make a new r only once, and then call .Next in your loop. The
numbers repeat because by re-executing Dim r as new Random() at each
iteration, a new Random object initialized with the same timer value. When
run in debug, things are slowed down enough so the timer ticks enough to make
the new Random objects that are seeded differently.
 
Thank you for your help. That seemed to fix it.

AMercer said:
You want to make a new r only once, and then call .Next in your loop. The
numbers repeat because by re-executing Dim r as new Random() at each
iteration, a new Random object initialized with the same timer value. When
run in debug, things are slowed down enough so the timer ticks enough to make
the new Random objects that are seeded differently.
 
Back
Top