Non-repetitive random seek in a range Algorithm

后端 未结 7 1745
终归单人心
终归单人心 2021-01-24 05:36

I\'m looking for an efficient algorithm that produces random values within a range, without repetitions.

In pseudo-code: (in class Rand)

  Rand(long from         


        
7条回答
  •  無奈伤痛
    2021-01-24 06:06

    If you don't require every number from the interval to appear eventually, you can use a linear congruental generator:

    int getNumber() {
        seed = (seed * A + C) mod (to-from);
        return seed + to;
    }
    

    It's periodical, the new period begins when seed becomes equal to the initial value, and the length of the period depends on A and C choice.

    Pros: O(1) time and space, cons: not every number from the interval will appear.

    For intervals of length 2^m, take a look at http://en.wikipedia.org/wiki/Linear_feedback_shift_register I did not use it, but wikipedia says it is possible it to be maximum-length, i.e. you can have all numbers (except one) appear in the output.

提交回复
热议问题