0

I am calling a method instance called buy. My method randomly generates a string of digits and numbers. My for loop appears to be going to fast for the method to change the string because I get the same string like 2-3 times in a row before getting a new string. when i add a System.Threading.Thread.Sleep(100); I am getting random number like the way it is supposed to be. The problem is that it is way too slow and i feel like there must be a better way. is there a way to get random string each time without invoking the Sleep() method?

for (int i = 0; i < exit; i++)
{
    ticket = buy.SetNum();
    Console.WriteLine("Wellcome Mr.Nissan. The winning numbers for Lotto max are:");
    Console.WriteLine(ticket);
    System.Threading.Thread.Sleep(25);
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
soso
  • 311
  • 1
  • 4
  • 13
  • 2
    What does `buy.SetNum()` do? – Hayden Oct 26 '15 at 04:41
  • Without seeing what's going on in `buy.SetNum()` it's impossible to tell where the problem is, since the code you posted in and of itself doesn't have any bits that vary. – millimoose Oct 26 '15 at 04:42
  • 1
    How are you generating the random numbers? If you are creating a new instance of the `Random` class each time, you will get this behavior because the default seed is the current time which will not be different if you call it quickly. – David Oct 26 '15 at 04:42
  • Also, is the variable (or field?) `ticket` set anywhere else in your code? – millimoose Oct 26 '15 at 04:43

3 Answers3

4

Yes, this is a problem with your random number generator - not with the code you posted in the question.

consider the following:

public int GenRandomNum()
{
   var r = new Random();
   return r.Next()
}

You are generating a new random class based on the same seed if you call it in the same tick, and it will generate the same number. Moving the random initialization out side of the method will fix the problem, like so:

private Random _rand = new Random();
public int GenRandomNum()
{
   return _rand .Next()
}
caesay
  • 16,932
  • 15
  • 95
  • 160
2

You haven't included the code that actually creates the random number but I suspect you're creating a new instance of the random number generator each time around the loop.

What you need to do instead, is create one instance of the random number generator (outside of the loop) and reuse it for each random number generator .Next() call.

lzcd
  • 1,325
  • 6
  • 12
0

Move the random number generation into into the loop:

var rnd = new Random(); 

for (int i = 0; i < exit; i++)
{
    var ticket = rnd.Next();
    Console.WriteLine("Wellcome Mr.Nissan. The winning numbers for Lotto max are:");
    Console.WriteLine(ticket);
}

I can't tell you why exactly your posted code wasn't working without seeing the buy.SetNum(); method code.

RagtimeWilly
  • 5,265
  • 3
  • 25
  • 41