Looking for an algorithm to spit out a sequence of numbers in a (pseudo) random order

后端 未结 10 1987
迷失自我
迷失自我 2021-02-03 15:33

Suppose I have a sequence of numbers: {n, n+1, n+2, ... n + m}

Without storing the numbers ahead of time I want to create a function f(), which given the sequence {1,2,3

10条回答
  •  广开言路
    2021-02-03 16:01

    If you want a 1:1 mapping, go with Fisher-Yates as mentioned in the other answers.

    If you don't care about 1:1 mapping, and you just need all of the resulting values to be from the given sequence (with the possibility of repeats), then you can use a random function with a specified range.

    For example, in C++, you could use rand() in the following way -

    result = rand() % (m+1) + n
    

    So for your example,

    result = rand() % 8 + 10
    

    Would produce an integer between 10 and 17.

提交回复
热议问题