避免重复随机 [英] 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();
我需要做一个打印7开奖号码的程序,但没有重复。在code以上版画在(1-37)范围内7个随机数字,但重复appaer。我需要一种方法来prevent重复号码出现。
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.
推荐答案
最简单的办法国际海事组织将生成的序列的所有的可能数量(即1-37),洗牌的收集,再取前七个结果。
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.
搜索堆栈溢出的费雪耶茨洗牌C#会发现很多的例子。
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();
这篇关于避免重复随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!