如果只是生成一个随机数,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;
}