您的位置:首页 > 编程语言 > C#

C#中生成不重复随机数

2015-11-03 08:45 681 查看
如果只是生成一个随机数,C#中的Random函数就足够用了,但如果需要生产若干个随机数,且这些数不能重复,就需要自己来写相应的方法了。

1.使用List<int>来存储随机数,List.Contain方法来判断生成的随机数是否已经存在

以在1-10中取5个不重复的随机数为例

public List<int> Generate1()
{
Random random = new Random();
List<int> result = new List<int>();
int temp;
while (result.Count < 5)
{
temp = random.Next(0, 11);
if (!result.Contains(temp))
{
result.Add(temp);
}
}
return result;
} 2.在一个List中中存储所有可能的数,每次随机取出一个,并在List中把它移除
以在1-10中取5个不重复的随机数为例

public List<int> Generate2()
{
List<int> all = new List<int>();
List<int> result = new List<int>();
Random random = new Random();

for (int i = 0; i < 11; i++)
{
all.Add(i);
}

for (int j = 0; j < 5; j++)
{
int index = random.Next(0, all.Count - 1);
result.Add(all[index]);
all.RemoveAt(index);
}

return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# 随机数 不重复