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.