Generate non-repeating, no sequential numbers

后端 未结 2 493
我在风中等你
我在风中等你 2020-12-07 05:58

how does one use code to do this:

produce 15 random numbers [EDIT: from 1 - 15] that are not in any order, and that only occur once eg.

1 4, 2, 5, 3, 6, 8, 7

2条回答
  •  渐次进展
    2020-12-07 06:48

    Generate the full list, then shuffle it.

    Python:

    import random
    r = range(1, 16)
    random.shuffle(r)
    

    A random number generator by itself can, almost by definition, not do what you want. It would need to keep track of all the numbers already generated, which would be as memory-hungry as the solution sketched above.

提交回复
热议问题