Reputation: 94
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?
Upvotes: 3
Views: 7807
Reputation: 62003
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.
Upvotes: 9
Reputation: 460340
With a loop:
int getRanNum2 = ran.Next(10);
while(getRanNum2 == getRanNum1)
getRanNum2 = ran.Next(10);
Upvotes: 14