Random array generation with no duplicates

前端 未结 9 957
無奈伤痛
無奈伤痛 2020-11-28 12:48

I am trying to create something that generates a random array with no duplicate values. I\'ve already looked at other answers but none seem to help me understand. I cannot t

9条回答
  •  粉色の甜心
    2020-11-28 12:48

    There are 2 solutions to choose from:

    1. Generate random numbers using something like rand() and check for duplicates.

    2. Find a mathematical sequence that is strictly monotonic (preferably strictly increasing) and get its terms as members of your array. Then, you can shuffle your array. The result will not be truly random, but neither using rand() won't. rand() uses a simillar tehnique, and that is why we need to set the seed with something changeing, like time. You can use time for example to generate the first element of the sequence, and with a good sequence your results will be at least decent. Note that the sequence MUST be strictly monotonic, to avoid generation of duplicates. The sequence need not be too complex. For example, if you get unix time modulo 10000 as the first term and then you generate other terms using a reccurence like x[i] = x[i-1] + 3*x[i-2] should be fine. Of course, you may use more sophisticated sequences too, but be careful at overflow (as you can't apply modulo operator to the result, because it would not be increasing anymore) and the number of digits you would like to have.

提交回复
热议问题