I have a lottery application in C# which takes in the number of numbers to draw and also the maximum number to draw.I have coded up to creating an array holding the required random numbers but I need them to be unique and am having trouble doing it.I would be very grateful if someone could give me some advice on this,Thanks
Here is my code so far:
class Lottery
{
static int[] numberHolder; //array to be filled with numbers up to an
//amount entered by the user eg 42 Max
static int[] drawHolder; //array to hold the each random number
//drawn from the pool of numbers eg 7 numbers
public Lottery() //Lottery class Constructor
{
}
//method which takes in a number limit and amount of numbers to be drawn
public String drawNumbers(int numLimit, int numAmount)
{
Random RandomNumber = new Random();
for (int i = 0; i < numLimit ; i++) //loop to fill up numberHolder array
// with predefined limit of numbers
{
numberHolder[i] = i++;
}
for (int i = 0; i < numAmount; i++)
{
// code to pick unique random numbers no greater than numAmount
// and add them to the drawHolder[] array
drawHolder[i] = RandomNumber.Next(1, numLimit);
}
//return the drawHolder array to String
return null;
}
}
This is easily achieved using a shuffling algorithm on an array of non-repeating integers:
I'd use Enumerable.Distinct like this:
In most lotteries where
numLimit
is large andnumAmount
is 10 or less, this method is more efficient than creating and shuffling an array of lengthnumLimit
.If real money is involved, you should use a better randomness generator than
Random
orGuid
. Here's a fullLottery
class that uses a cryptographic random number generator (based on Microsoft's RNGCryptoServiceProvider).