简体   繁体   English

如何使随机数(低于 50 毫秒)不会重复两次

[英]How to make so Random Number (under 50 milliseconds) wont repeat twice

I'm making script and it generates random numbers in milliseconds (Range 20-100), let's say it generated delays: 30, 40, 42 (All < (less than) 50)我正在制作脚本,它以毫秒为单位生成随机数(范围 20-100),假设它产生了延迟:30、40、42(全部 <(小于)50)

Now I want to make it so 4th delay cant be again less than 50, I tried this:现在我想让它第四次延迟不能再小于 50,我试过这个:

I tried using for loop, but my when i use this code script doesn't work at all anymore / it won't toggle or anything.我尝试使用 for 循环,但是当我使用此代码脚本时,我的脚本根本不起作用/它不会切换或任何东西。

Just imagine you made script and it generates random numbers from 20-100 and you dont want 4 in row delays that are less than 50, what would you do?试想一下,您编写了脚本,它生成了 20-100 的随机数,并且您不希望 4 行延迟小于 50,您会怎么做? Thanks.谢谢。

        for (int i = 0; i < 4;)
        {

            // Total Delay aka delay1+delay2
            if (totaldelay < 50)
            {
                i++;
            }

            // Should make totaldelay > 50
            if (i == 3)
            {
                delay1 = RandomInt(75, 105);
            }

            // Reset to 0 so it checks from 0 again
            if (total > 50)
            {
                i = 0;
            }





        }

If I understand the question correctly, you don't want four consecutive numbers to be all less than 50. You can achieve this by simply keeping a count and adjusting your behaviour so that you generate a different number if the previous three were all less than 50.如果我正确理解了这个问题,您不希望四个连续的数字都小于 50。您可以通过简单地保持计数并调整您的行为来实现这一点,以便在前三个都小于时生成不同的数字50.

If you're looking for a standalone C++ function to do that (give you one random number per call, with your specific added limitations), you can use something like:如果您正在寻找一个独立的 C++ function 来执行此操作(每次调用给您一个随机数,并带有您的特定附加限制),您可以使用类似的东西:

int getMyRand() {
    // Keep track of how many consecutive under-50s already done.
    // Careful in multi-threaded code, may need thread-local instead.

    static int consecUnder50 = 0;
    int number;

    // If last three were all < 50, force next one to be >= 50.

    if (consecUnder50 == 3) {
        number = rand() % 51 + 50;  // 50-100 (inclusive).
    } else {
        number = rand() % 81 + 20;  // 20-100 (inclusive).
    }

    // If less, record it, otherwise restart count.

    if (number < 50) {
        ++consecUnder50;
    } else {
        consecUnder50 = 0;
    }

    // Give caller the number.

    return number;
}

Don't forget to seed the random number generator before using this, and be aware that C++ has better random number generators, although rand() is usually fine unless you're a statistician or cryptographer:-)不要忘记在使用它之前为随机数生成器播种,并注意 C++ 具有更好的随机数生成器,尽管rand()通常很好,除非你是统计学家或密码学家:-)

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

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