产生不同随机数在C# [英] Generate distinct random numbers in C#

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

问题描述

只是想知道,如果你能确认以下code是有效的,并建议如果有给它更好的方法?

我试图产生1和100000之间不同随机数的集合。

 随机兰特=新的随机();
名单<的Int32>结果=新名单,其中,的Int32>();
对于(的Int32 I = 0; I< 300;我++)
{
    INT32 curValue = rand.Next(1,100000);
    而(result.Exists(价值=>值== curValue))
    {
        curValue = rand.Next(1,100000);
    }
    result.Add(curValue);
}
 

解决方案

是的,据我所知道的,code不正是你想要的。

通过列表循环检查每个值不是非常有效的。你可以把一个 HashSet的&LT的值; INT> 加快ckeck

由于'HashSet'没有preserve的项目的顺序,你仍然需要在列表虽然:

 随机兰特=新的随机();
名单< INT>结果=新名单,其中,INT>();
HashSet的< INT>检查=新的HashSet<诠释>();
对于(的Int32 I = 0; I< 300;我++){
    INT curValue = rand.Next(1,100000);
    而(check.Contains(curValue)){
        curValue = rand.Next(1,100000);
    }
    result.Add(curValue);
    check.Add(curValue);
}
 

Just wondering if you could confirm that the following code is valid and advise if there are better alternatives to it?

I am attempting to generate a collection of distinct random numbers between 1 and 100000.

Random rand = new Random();
List<Int32> result = new List<Int32>();
for (Int32 i = 0; i < 300; i++)
{
    Int32 curValue = rand.Next(1, 100000);
    while (result.Exists(value => value == curValue))
    {
        curValue = rand.Next(1, 100000);
    }
    result.Add(curValue);
} 

解决方案

Yes, as far as I can tell, the code does exactly what you want.

Looping through the list to check each value is not very efficient. You can put the values in a HashSet<int> to speed up the ckeck.

As the ´HashSet´ doesn't preserve the order of the items, you still need the List though:

Random rand = new Random();
List<int> result = new List<int>();
HashSet<int> check = new HashSet<int>();
for (Int32 i = 0; i < 300; i++) {
    int curValue = rand.Next(1, 100000);
    while (check.Contains(curValue)) {
        curValue = rand.Next(1, 100000);
    }
    result.Add(curValue);
    check.Add(curValue);
}

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

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