get random value from a PHP array, but make it unique

后端 未结 9 1064
挽巷
挽巷 2020-12-16 19:44

I want to select a random value from a array, but keep it unique as long as possible.

For example if I\'m selecting a value 4 times from a array of 4 elements, the s

9条回答
  •  囚心锁ツ
    2020-12-16 20:31

    If you do not care about what particular values are in the array, you could try to implement a Linear Congruential Generator to generate all the values in the array.

    LCG implementation

    Wikipedia lists some values you can use, and the rules to select the values for the LCG algorithm, because the LCG algorith is deterministic it is guaranteed not to repeat a single value before the length of the period.

    After filling the array with this unique numbers, you can simply get the numbers in the array 1 by 1 in order.

提交回复
热议问题