Language agnostic 周期可调的PRNG

Language agnostic 周期可调的PRNG,language-agnostic,random,Language Agnostic,Random,我需要构建一个具有可调周期的就地伪随机数生成器。此外,一段时间内不得发生碰撞。也就是说,以下值必须返回true: // prng is "generated" at run-time // (though a by-hand solution would work) bool test(func prng, int period) { int seed = 0; // Any number should work int cur = seed; for (int i

我需要构建一个具有可调周期的就地伪随机数生成器。此外,一段时间内不得发生碰撞。也就是说,以下值必须返回true:

// prng is "generated" at run-time
// (though a by-hand solution would work)

bool test(func prng, int period) {
    int seed = 0;  // Any number should work
    int cur = seed;

    for (int i = 0; i <= period; ++i) {
        cur = prng(cur);

        if (cur == seed) {
            if (i == period) {
                // We hit our period on target
                return true;
            }

            // Period too low (we hit our seed already!)
            return false;
        }
    }

    // Period too high
    return false;
}
//prng在运行时“生成”
//(尽管手动解决方案可行)
布尔测试(函数周期,整数周期){
int seed=0;//任何数字都可以
int cur=种子;

对于(int i=0;i我认为一个很好的候选是斐波那契线性反馈移位寄存器(LFSR)

您可以从中获得相关信息和算法

只是一段摘录:

The initial value of the LFSR is called the seed, and because the operation of the register is deterministic, the stream of values produced by the register is completely determined by its current (or previous) state. Likewise, because the register has a finite number of possible states, it must eventually enter a repeating cycle. However, an LFSR with a well-chosen feedback function can produce a sequence of bits which appears random and which has a very long cycle. LFSR的初始值称为种子,因为操作 寄存器的类型是确定性的,由 寄存器完全由其当前(或以前)状态决定。 同样,由于寄存器具有有限数量的可能状态,它必须 最终进入一个重复的循环。然而,一个选择正确的LFSR 反馈函数可以产生一系列看起来随机的位 它有一个很长的周期。 唯一的问题是LFSR的周期始终为2N-1形式。
您可以克服这一点,注意对于任何想要的周期P,选择给出“下一个”2N-1值的N可能会从循环中留下2(N-1)-1个数字进行suppress(因为如果您需要suppress超过该值,只需使用N-1生成)

所以,为了压制k值(k=((2N-1)-p)⋳ {1…,2(N-1)-1})您可以添加一些逻辑,例如

如果(Mod(cur,2(N-1)+1-k)=0),则
cur=Mod(cur+1,2N-1)

If (Mod(cur,2(N-1)+1-k) == 0) Then cur=Mod(cur+1,2N-1)