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

后端 未结 10 1958
迷失自我
迷失自我 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:04

    This question is analogous to shuffling a deck of (m + 1) cards, numbered [n, ..., n + m]. Notice that the numbering (and thus n) is unimportant; what matters is that we can tell the cards apart. (You can simply add the n back later if desired.)

    To do what you want, you can perform a Fisher-Yates shuffle and just keep track of which indices have been selected for shuffling so far. This will allow you to avoid storing another copy of the values themselves, as requested.

提交回复
热议问题