简体   繁体   English

如何创建一个不重复的随机数?

[英]How to create a random number that doesn't repeat?

I have a variable that will either become 1 or 0, and all I know is rand()% 2 . 我有一个将变为1或0的变量,我所知道的只是rand()% 2

The problem is when I loop it it keeps becoming either 1 for about four times straight then 0, or 0 for straight 6 times then 1. 问题是,当我循环播放时,它会变成1连续约4倍,然后变为0,或者0连续6倍,然后变为1。

I want it to be like 0 for once or twice, then 1, then 0 again. 我希望它像0一样代表一两次,然后是1,然后再次是0。 Something like that. 这样的事情。 Is it possible to do this? 是否有可能做到这一点?

If you really want to have only runs of 1 or 2, while maintaining some randomness, you can keep track of it like this; 如果您确实希望只运行1或2,同时又保持一定的随机性,则可以像这样跟踪它;

int nextRandomIshThing( ) {
    static int n1 = 0;
    static int n2 = -1;
    if( n1 != n2 ) {
        n1 = n2;
        // use a high-order bit, which supposedly has better randomness
        // 14 because the standard guarantees that rand() produces at least
        // 15 bits of randomness (not sure why that exactly)
        n2 = (rand( ) >> 14) & 1;
    } else {
        n2 = !n2;
    }
    return n2;
}

http://codepad.org/HTTtPezu http://codepad.org/HTTtPezu

But beware that depending on how you're using this, it means that users can "game" your system; 但是请注意,这取决于您的使用方式,这意味着用户可以“玩”您的系统; "I've seen 2 1's, therefore the next must be 0!". “我看过2个1,因此下一个必须是0!”。 A truly random source will always produce long sequences. 真正的随机源将始终产生长序列。 There is a 1 in 8 chance for a truly random source to produce 4 1's or 0's in a row, and a 1 in 16 chance of 5. When you consider that you don't care where exactly the run starts, this becomes even more likely. 真正的随机源有八分之一的机会连续产生4个1或0,而有16分之一的机会有5个。当您认为不在乎运行从何处开始时,这种可能性就更大了。可能。 If you want to be fair, embrace this instead of fighting it! 如果您想公平一点,那就拥抱它而不是与之抗争吧!

Oh and don't forget to srand . 哦,别忘了srand

You either want a random number or a predictable result. 您需要一个随机数或可预测的结果。 You can't choose the amount of randomness, the whole point of a random number generator is to generate something unpredictable. 您不能选择随机性的数量,随机数生成器的全部要点是生成不可预测的东西。

But what you can do is simply use the random number in a different way. 但是您可以做的就是简单地以不同的方式使用随机数。 If you want, say, at most, 4 consecutive runs of 0 or 1 you could determine the count of consecutive numbers using rand and generate the numbers yourself: 如果最多只需要连续运行4次0或1,则可以使用rand确定连续数字的计数,然后自己生成数字:

int number = 0;
for (int runs = 0; runs < 100; ++runs) {
    int count = rand() % 4;
    for (int i = 0; i < (count ? count : 1); ++i) { // Ensure at least 1 run
        printf("%d", number);
    }
    number = 1 - number;
}

See codepad example: http://codepad.org/OKe5Agib 请参阅键盘示例: http : //codepad.org/OKe5Agib

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM