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;
}
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#调用COM组件
- C#实现把指定数据写入串口
- C#动态创建button的方法
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#使用加边法计算行列式的值
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- C#实现子窗体与父窗体通信方法实例总结
- C#通用邮件发送类分享
- C#中this的用法集锦
- C#.NET获取拨号连接的宽带连接方法
- C#异步绑定数据实现方法
- C#实现AddRange为数组添加多个元素的方法
- C#中Equality和Identity浅析
- C#生成饼形图及添加文字说明实例代码
- C#判等对象是否相等的方法汇总
- C#简单的向量用法实例教程
- C#实现基于链表的内存记事本实例
- C#托管堆对象实例包含内容分析