且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

迭代生成自然数的排列

更新时间:2023-11-28 14:30:58

您正在寻找的是函数形式的伪随机排列,例如 f ,该函数映射从1开始的数字以伪随机双射的方式从N到N到1到N的数字上.然后,要生成伪随机排列的 n 个数字,只需返回 f(n)

What you are looking for is a pseudo-random permutation in the form of a function, say f, that maps numbers from 1 to N onto numbers from 1 to N in a pseudo-random bijective way. Then, to generate the nth number in a pseudo-random permutation, you just return f(n)

这与加密本质上是相同的问题.带密钥的分组密码是伪随机双射函数.如果您以某种顺序一次将所有可能的纯文本块送入,它将以不同的伪随机顺序一次一次返回所有可能的密文块.

This is essentially the same problem as encryption. A block cipher with a key is a pseudo-random bijective function. If you feed it all possible plaintext blocks exactly once in some order, it will return all possible ciphertext blocks exactly once in a different, pseudo-random order.

因此,要解决像您这样的问题,您实际上要做的是创建一个密码,该密码适用于从1到N的数字,而不是256位块或其他任何数字.您可以使用密码学中的工具来做到这一点.

So to solve a problem like yours, what you essentially do is create a cipher that works on numbers from 1 to N instead of 256-bit blocks or whatever. You can use the tools from cryptography to do this.

例如,您可以使用Feistel结构构造置换函数( https://en.wikipedia. org/wiki/Feistel_cipher ),就像这样:

For example, you can construct your permutation function with a Feistel structure (https://en.wikipedia.org/wiki/Feistel_cipher) like this:

  1. 让W为floor(sqrt(N)),让该函数的输入为x
  2. 如果x< W ^ 2,然后将x分为2个字段,从0到W-1:h = floor(x/W)和l = x%W.哈希h以产生从0到W-1的值,并设置l =(l + hash)%W.然后交换字段-让x = l * W + h
  3. x =(x +(N-W ^ 2))%N
  4. 重复步骤(2)和(3)几次.您做得越多,结果看起来就越随机.步骤(3)确保x <0. W ^ 2在许多回合中都是正确的.

由于此函数由多个步骤组成,每个步骤都将以双射的方式将0到N-1的数字映射到0到N-1的数字,因此整个函数也将具有此属性.如果您输入0到N-1之间的数字,则会以伪随机顺序将它们取回来.

Since this function consists of a number of steps, each of which will map the numbers from 0 to N-1 onto the numbers from 0 to N-1 in a bijective way, the entire function will also have this property. If you feed it the numbers from 0 to N-1, you'll get them back out in a pseudo-random order.