3

I would like to generate two random numbers that are different from each other. For example, if the first random number generates 5, I want the next random number generated to not equal 5. This is my code thus far:

Random ran = new Random();
int getRanNum1 = ran.Next(10);
int getRanNum2 = ran.Next(10);

How do I tell getRandNum2 to not equal the value generated in getRandNum1?

jipot
  • 304
  • 3
  • 13
  • 34
  • 3
    You do realize that that makes `getRanNum2` a little less random? Especially on a small range like `0..9`. – H H Oct 25 '13 at 22:41

2 Answers2

14

With a loop:

int getRanNum2 = ran.Next(10);
while(getRanNum2 == getRanNum1)
    getRanNum2 = ran.Next(10);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
9

While the loop-and-check approach is likely suitable here, a variant of this question is "How to get N distinct random numbers in a range (or set)?"

For that, one possible alternative (and one that I like, which is why I wrote this answer) is to build said range (or set), shuffle the items, and then take the first N items.

An implementation of the Fischer-Yates shuffle can be found in this answer. Slightly cleaned up for the situation:

void Shuffle (int arr[]) {
  Random rnd = new Random();
  for (int i = arr.Length; i > 1; i--) {
    int pos = rnd.Next(i);
    var x = arr[i - 1];
    arr[i - 1] = arr[pos];
    arr[pos] = x;
  }
}

// usage
var numbers = Enumerable.Range(0,10).ToArray();
Shuffle(numbers);
int getRanNum1 = numbers[0];
int getRanNum2 = numbers[1];

Since we know that only N (2) elements are being selected, the Shuffle method above can actually be modified such that only N (2) swaps are done. This is because arr[i - 1], for each i, is only swapped once (although it can be swapped with itself). In any case, this left as an exercise for the reader.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220