本文介绍了避免随机重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 个彩票号码,但不能重复.上面的代码打印了 (1-37) 范围内的 7 个随机数,但重复了 appaer.我需要一种方法来防止出现重复的数字.

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.

推荐答案

IMO 最简单的方法是生成所有 可能的数字(即 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.

在 Stack Overflow 上搜索Fisher-Yates shuffle C#"会找到很多例子.

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

实际上,您可以修改 Fisher-Yates shuffle 以在获取结果时产生结果,因此您可以编写如下方法:

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();

这篇关于避免随机重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 05:52