不产生重复的随机数 [英] Generate random numbers without repeats

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

问题描述

我想不重复生成随机数,直到全没了,然后再与初始数据集生成随机数。

I want to generate random numbers without repeats till all gone, then again generating random numbers with the initial dataset.

我知道保持已生成的数字中的阵列,并通过他们loopin检查它是否被alredy生成或方法扣除从阵列产生,并与新的数组随机数的数字。

I know keeping already generated numbers in an array and loopin through them to check whether it is alredy generated or the method deducting the numbers that are generated from the array and randomize numbers with the new array.

我要的是不是这些方法,如果有一种方式,是使用高效的数据结构将是相当不错的,如果是任何其他方法也行

What I want is not those methods, if there is a way that is efficient using data structures will be quite nice, if it is any other method also ok

感谢

推荐答案

假设你想在同一时间产生1000独特的随机数和present他们一些code之一。当你用尽这些数字,你想再次相同的号码present,但在不同的顺序。

Say you want to generate 1,000 unique random numbers and present them to some code one at a time. When you exhaust those numbers, you want to present the same numbers again, but in a different sequence.

要生成的数字,则使用哈希表。在C#中,它应该是这样的:

To generate the numbers, use a hash table. In C#, it would look like this:

const int MaxNumbers = 1000;
HashSet<int> uniqueNumbers = new HashSet<int>();
Random rnd = new Random();
// generate random numbers until there are 1000 in the hash table
while (uniqueNumbers.Count < MaxNumbers)
{
    uniqueNumbers.Add(rnd.Next());
}
// At this point you have 1,000 unique random numbers
// Put them in an array
int[] myNumbers = uniqueNumbers.ToArray();

这工作,因为 HashSet.Add 方法拒绝重复。而且它的速度非常快,因为在查找哈希表为O(1)。

This works because the HashSet.Add method rejects duplicates. And it's very fast because lookup in the hash table is O(1).

现在,您可以通过在0设置当前索引为他们服务,并在每次请求一些时间增加了。是这样的:

Now, you can serve them by setting a current index at 0 and increment it every time a number is requested. Something like:

int ixCurrent = 0;
int GetNextNumber()
{
    if (ixCurrent < MaxNumbers)
    {
        ++ixCurrent;
        return myNumbers[ixCurrent-1];
    }

但是,当 ixCurrent 逃跑数组到底该干什么?进入费雪耶茨洗牌的:

But what to do when ixCurrent runs off the end of the array? Enter the Fisher-Yates Shuffle:

    // out of numbers. Shuffle the array and return the first one.
    for (int i = MaxNumbers-1; i > 0; --i)
    {
        int j = rnd.Next(i+1);
        int temp = myNumbers[i];
        myNumbers[i] = myNumbers[j];
        myNumbers[j] = temp;
    }
    ixCurrent = 1;
    return myNumbers[0];
}

如果你知道你想要回号码是一个特定的范围内(即,要返回随机顺序号0-999),那么你只需填写的价值观和0-999洗牌数组吧。

If you know that the numbers you want to return are within a particular range (that is, you want to return the numbers 0-999 in random order), then you just fill an array with the values 0-999 and shuffle it.

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

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