当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Avoiding random duplicates

问题描述:

System.Random generator = new Random(DateTime.Now.Millisecond);

int[] lotteryNumber = new int[7];

Console.WriteLine("Your lottery numbers: ");

for (int i = 0; i<7; i++)

{

lotteryNumber[i] = generator.Next(1, 37);

Console.Write("{0} ",lotteryNumber[i]);

}

Console.ReadLine();

I need to make a program that prints 7 lottery numbers, but without duplicates. The code above prints 7 random numbers in the range of (1-37), but duplicates appaer. I need a way to prevent duplicate numbers from appearing.

网友答案:

The simplest approach IMO would be to generate a sequence of all the possible numbers (i.e. 1-37), shuffle the collection, then take the first seven results.

Searching on Stack Overflow for "Fisher-Yates shuffle C#" will find lots of examples.

In fact, you could modify the Fisher-Yates shuffle to yield results as you took them, so you could write a method such as:

var numbers = Enumerable.Range(1, 37).Shuffle().Take(7).ToList();
网友答案:

You could take a dictionary but make sure that you prevent duplicate key insertion. Keys of dictionary would serve as the unique numbers you need

网友答案:

You could toss them into a HashSet<int>. If you Add and it returns false, generate a new number.

网友答案:

If you're trying to pick numbers from a range without repetitions, you need to create an array of all the possible numbers and then "shuffle" a random selection out:

int[] allPossibleNumbers = Enumerable.Range(1, 37).ToArray();
int[] lotteryNumber = new int[7];
for (int i = 0; i < 7; i++)
{
    int index = r.Next(i, 37);
    lotteryNumber[i] = allPossibleNumbers[index];
    allPossibleNumbers[index] = allPossibleNumbers[i];
    // This step not necessary, but allows you to reuse allPossibleNumbers
    // rather than generating a fresh one every time.
    // allPossibleNumbers[i] = lotteryNumber[i];
}
网友答案:

Generate a list with your 37 items. Then in your for, select one and delete the selected

网友答案:

Maybe this could help, if you get the existing number just try to find new one that isn't in the array:

static void Main(string[] args)
        {
            System.Random generator = new Random(DateTime.Now.Millisecond); int[] lotteryNumber = new int[7];

            Console.WriteLine("Your lottery numbers: ");
            for (int i = 0; i < 7; i++)
            {
                int lNumber = 0;
                do
                {
                    lNumber = generator.Next(1, 37);
                }
                while (lotteryNumber.Contains(lNumber));
                lotteryNumber[i] = lNumber;

                Console.Write("{0} ", lotteryNumber[i]);
            }
            Console.ReadLine();
        }
网友答案:
HashSet<int> set = new HashSet<int>();
System.Random generator = new Random(DateTime.Now.Millisecond);

while(set.Count < 7){
    set.Add(generator.Next(1,37);
}

That should work, since a HashSet will automatically ignore duplicates. Just loop until the set reaches the number of units you need. Only potential problem is it has the POTENTIAL (unlikely) to loop for a long time, but it should eventually respond.

网友答案:

so I took your original code...found some logic errors and added the fix you were looking for to prevent random number duplicates.

Enjoy!

 System.Random generator = new Random(DateTime.Now.Millisecond);
            int[] lotteryNumber = new int[7];
            int lowerBounds = 1;
            int upperBounds = 8;
            int maxNumberLotteryValues = 7;

            if ( ( upperBounds - lowerBounds ) < (maxNumberLotteryValues))
            {
                Console.Write("Warning: Adjust your upper and lower bounds...there are not enough values to create a unique set of Lottery numbers! ");

            }
            else
            {
                Console.WriteLine("Your lottery numbers: ");
                for (int i = 0; i < maxNumberLotteryValues; i++)
                {
                    int nextNumber = generator.Next(lowerBounds, upperBounds);
                    int count = lowerBounds;  //Prevent infinite loop

                    while ((lotteryNumber.Contains(nextNumber))
                        && (count <= upperBounds))
                    {
                        nextNumber = generator.Next(lowerBounds, upperBounds);
                        count++;  //Prevent infinite loop
                    }

                    lotteryNumber[i] = nextNumber;
                    Console.Write("{0} ", lotteryNumber[i]);
                }
            }

            Console.ReadLine();
分享给朋友:
您可能感兴趣的文章:
随机阅读: