Random selection

前端 未结 4 1799
长发绾君心
长发绾君心 2020-12-21 00:20

Given two integer numbers N and n (N >= n > 0), how do I generate random selection (without repetition!) of [0, N) with length = n? E.g. Given N = 5, n = 3 possible solution

4条回答
  •  梦毁少年i
    2020-12-21 01:03

    In python, this would be really easy:

    selection = random.shuffle(range(N))[:n]
    

    This is O(N) in memory, since the list of valid values is generated first and then shuffled in place, so it fails on your requirement :(

    You could try something like this:

    N = 5
    n = 3
    selection = set()
    while len(selection) < n:
        selection += pick_random_int(0, N)
    

    Which is essentially what Jon Skeet proposed. This will work well for n << N, but start to fail horribly with n close to N. In that case, though, the O(n) and O(N) memory solutions will converge anyway and your requirement is moot ;)

提交回复
热议问题