Create a random permutation of 1..N in constant space

前端 未结 6 726
旧巷少年郎
旧巷少年郎 2020-11-30 04:30

I am looking to enumerate a random permutation of the numbers 1..N in fixed space. This means that I cannot store all numbers in a list. The reason for that is that N can be

6条回答
  •  独厮守ぢ
    2020-11-30 04:34

    The fundamental weakness of LCGs (x=(x*m+c)%b style generators) is useful here.

    If the generator is properly formed then x%f is also a repeating sequence of all values lower than f (provided f if a factor of b).

    Since bis usually a power of 2 this means that you can take a 32-bit generator and reduce it to an n-bit generator by masking off the top bits and it will have the same full-range property.

    This means that you can reduce the number of discard values to be fewer than N by choosing an appropriate mask.

    Unfortunately LCG Is a poor generator for exactly the same reason as given above.

    Also, this has exactly the same weakness as I noted in a comment on @JerryCoffin's answer. It will always produce the same sequence and the only thing the seed controls is where to start in that sequence.

提交回复
热议问题