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;
}
}
There are a few options, you could use the
Contains
method.The Any() method.
In my opinion, you should change your approach.
Instead of thinking "I'll generate random indexes to pick my numbers", where you have to be sure you don't get any duplicates, I would simply shuffle the array and take the X first you need. That way, you don't need to worry about indexes or duplicates.
So your second for loop would be changed to
(Please note I've used
new Guid()
so you can remove yourRandomNumber
declaration line. As discussed before, a GUID is a unique value and not meant for to be used as a random gen. You could also usex => RandomNumber.Next()
, but if you really need a strong and reliable shuffe, read about Fisher-Yates)You can also replace your numberHolder array with a simple
Enumerable.Range
So your whole code would become (And please note I've changed your method name to use C# conventions, method names should be in PascalCase)
I would keep it simple:
Keep the declaration of the
Random
instance outside of the method to prevent returning identical sequences if you call the method in quick succession.Lots of ways to do this. You could sort and then compare
if array[i] == array[i+1]
.Sounds like shuffling your array is better than generating random numbers. You could do it like this:
Credit goes to @RohitArora.
It's too late but I use a Method named M_Randomizer created by me.