Avoiding random duplicates

后端 未结 9 1060
情深已故
情深已故 2020-12-03 19:52
System.Random generator = new Random(DateTime.Now.Millisecond);
int[] lotteryNumber = new int[7];

Console.WriteLine(\"Your lottery numbers: \");
for (int i = 0; i&l         


        
9条回答
  •  情书的邮戳
    2020-12-03 20:31

    HashSet set = new HashSet();
    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.

提交回复
热议问题