生成随机数而不重复.C# [英] Generating random numbers without repeating.C#

查看:142
本文介绍了生成随机数而不重复.C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我试图在c#的同一行上生成6个不同的数字,但是我面临的问题是某些数字在同一行上重复。这是我的代码

Hi everyone I am trying to generate 6 different numbers on the same line in c# but the problem that i face is some of the numbers are repeating on the same line.Here is my code to

List<int> listNumbers = new List<int>();
int numbers = rand.Next(1,49);
for (int i= 0 ; i < 6 ;i++)
    {
         listNumbers.Add(numbers);
         numbers = rand.Next(1,49);
    }

我的输出是

  17 23 23 31 33 48


推荐答案

对照先前的数字检查您生成的每个数字:

Check each number that you generate against the previous numbers:

List<int> listNumbers = new List<int>();
int number;
for (int i = 0; i < 6; i++)
{
  do {
     number = rand.Next(1, 49);
  } while (listNumbers.Contains(number));
  listNumbers.Add(number);
}

另一种方法是创建可能数字的列表,并删除您所需要的数字从列表中选择:

Another approach is to create a list of possible numbers, and remove numbers that you pick from the list:

List<int> possible = Enumerable.Range(1, 48).ToList();
List<int> listNumbers = new List<int>();
for (int i = 0; i < 6; i++)
{
  int index = rand.Next(0, possible.Count);
  listNumbers.Add(possible[index]);
  possible.RemoveAt(index);
}

这篇关于生成随机数而不重复.C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆