Looking for an algorithm to spit out a sequence of numbers in a (pseudo) random order

后端 未结 10 2097
迷失自我
迷失自我 2021-02-03 15:33

Suppose I have a sequence of numbers: {n, n+1, n+2, ... n + m}

Without storing the numbers ahead of time I want to create a function f(), which given the sequence {1,2,3

10条回答
  •  悲哀的现实
    2021-02-03 16:05

    There is a simple function that generates a permutation of [0..m-1] for a given m. Just pick a number k, relatively prime to m and let f(i)=(k*i) mod m. This always generates a permutation (no repeats on 0<=i). It works better if k is larger than m.

    For example, m=20, let k=137 (Python code, % means modulo):

     >>> [(137*i) % 20 for i in range(20)]
     [0, 17, 14, 11, 8, 5, 2, 19, 16, 13, 10, 7, 4, 1, 18, 15, 12, 9, 6, 3]
    

    This is a very simple PRNG, no guarantees about its statistical properties.

提交回复
热议问题