Generating shuffled range using a PRNG rather than shuffling

前端 未结 5 2005
孤城傲影
孤城傲影 2020-12-01 04:55

Is there any known algorithm that can generate a shuffled range [0..n) in linear time and constant space (when output produced iteratively), given an arbitrary seed value?

5条回答
  •  心在旅途
    2020-12-01 05:28

    Look into Linear Feedback Shift Registers, they can be used for exactly this. The short way of explaining them is that you start with a seed and then iterate using the formula

    x = (x << 1) | f(x)
    

    where f(x) can only return 0 or 1.

    If you choose a good function f, x will cycle through all values between 1 and 2^n-1 (where n is some number), in a good, pseudo-random way. Example functions can be found here, e.g. for 63 values you can use

    f(x) = ((x >> 6) & 1) ^ ((x >> 5) & 1)
    

提交回复
热议问题