-1

I am trying to write a simple program where I generate two numbers from a selection and put them in two text boxes, however sometimes the numbers are repeating and this of no use, the code I am currenty using is this:

Random myRandom = new Random();
int randomNumber = myRandom.Next(2, 4);
textBox1.Text = Convert.ToString(randomNumber);
int randomNumber2 = myRandom.Next(2, 4);
textBox2.Text = Convert.ToString(randomNumber2);

Could anyone please suggest a way to stop them repeating.

Thanks in advance.

Tomas Pastircak
  • 2,867
  • 16
  • 28
Tambo
  • 1
  • possible duplicate of [how to avoid number repeation by using random class in c#?](http://stackoverflow.com/questions/5602953/how-to-avoid-number-repeation-by-using-random-class-in-c). See also: http://stackoverflow.com/questions/1785744/how-do-i-seed-a-random-class-to-avoid-getting-duplicate-random-values – tnw Apr 22 '14 at 18:09

1 Answers1

1

Because your range is so small (you can only get 2 numbers: 2 and 3), you are very likely to get a duplicate! Its like flipping a coin:

Heads, Heads = 25% (duplicate)

Heads, Tails = 50%

Tails, Tails = 25% (duplicate)

In fact, you will get a duplicate 50% of the time!

There are a lot of ways to get around this, but if you will always have 2 (and exactly two) selections, you can just change your code to:

Random myRandom = new Random();
int randomNumber = myRandom.Next(2, 4);
textBox1.Text = Convert.ToString(randomNumber);
int randomNumber2 = myRandom.Next(2, 4);

while (randomNumber2 == randomNumber)
   randomNumber2 = myRandom.Next(2, 4);

textBox2.Text = Convert.ToString(randomNumber2);

Basically you just loop until you get a different value. You should also note that calling this function repeatedly (very quickly) could cause problems since you are initializing the Random object each time. Since it uses a time-based seed, having two initializations close to each other in time could cause "repeated" results. In general it is considered better practice to put the Random class instance at the class level (instead of the function level).

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117