var list = new List<int>(){1,17,18,21,30};
Random rnd = new Random(DateTime.Now.Second);
int r;
do
{
r = rnd.Next(1, 30);
}
while (list.Contains(r));
但我认为这是一个愚蠢的解决方案,谁能给我一个更优化的方法?
如果有一种方法可以防止 Random 实例返回它已经返回的数字,那就更好了。
万一有人想知道为什么我需要这个它是洗牌 3 字节数组并将它们组合成一个字节数组并生成 3 字节数组的第一步,该数组保持原始数组中索引的原始顺序。
最佳答案
是的,提高效率的一件事是使用 HashSet<int>
而不是 List<int>
HashSet 的查找比 List 快得多(但是 HashSet 的构造函数成本会稍微高一些)。
此外,如果输入列表始终是相同的数字,则将其移出函数以帮助减少首次生成 HashSet 的成本开销。
由于现在顺序很重要,根据我的个人经验(请根据您自己的情况进行测试和分析),在列表中大约 14 个项目之后,将列表转换为 HashSet 并进行查找比在中进行查找更快列表本身。
var list = new List<int>(){1,17,18,21,30};
Random rnd = new Random(DateTime.Now.Second);
int r;
//In this example with 5 items in the list the HashSet will be slower do to the cost
// of creating it, but if we knew that the 5 items where fixed I would make this
// outside of the function so I would only have to pay the cost once per program
// start-up and it would be considered faster again due to amortized start-up cost.
var checkHashSet = new HashSet<int>(list);
do
{
r = rnd.Next(1, 30);
}
while (checkHashSet.Contains(rnd.Next(1, 30))); //Shouldent this be "r" not "rnd.Next(1,30)"?
关于c# - 获得一个随机数,只要它不在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20891422/