Random number generator with no duplicates

You need to store them in a collection and each time you pick a new number you need to make sure it's not present already, otherwise you need to generate a new number until you find a unique number.

Instead of this, I would generate a sequence between 1 and 49, shuffle them and pick 6 number out of the sequence, for example:

var rnd = new Random();
var randomNumbers = Enumerable.Range(1,49).OrderBy(x => rnd.Next()).Take(6).ToList();

You can't. You've only specified that each number be a random number from 1 to 49, not that it shouldn't match any duplicates.

Since you've got a relatively small set of numbers, your best bet is probably to draw the random numbers, put them into a HashSet, then if you need more, pull more. Something like this:

HashSet<int> numbers = new HashSet<int>();
while (numbers.Count < 6) {
    numbers.Add(random.Next(1, 49));
}

Here you're taking advantage of the HashSet's elimination of duplicates. This won't work with a List or other collection.


Returning repeat values is a necessity in order for a generator to satisfy a necessary statistical property of randomness: the probability of drawing a number is not dependent on the previous numbers drawn.

You could shuffle the integers in the range 1 to 49 and return the first 6 elements. See http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle for more details on such a shuffler.

However, I think you get a slight statistical bias by doing this.

The best way is probably to use random.Next(1, 49); and reject any repeat. That will be free from statistical bias and the fact that you're only wanting 6 from 49 possibilities, the number of collisions will not slow the algorithm appreciably.