Random selection

前端 未结 4 1807
长发绾君心
长发绾君心 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条回答
  •  醉话见心
    2020-12-21 01:03

    The simple (but potentially very inefficient) solution is just to build a list by repeatedly picking a value in the desired range, and checking whether or not you've already picked it. This has an unbounded maximum time, because you could always end up accidentally picking something you've already picked.

    I have a vague inkling of an O(n2) solution which in each iteration picks a value in the range [0, N - i) where i is the number of elements you've already got... and then mapping that new value onto the range [0, N) by going through the existing picked elements and adding 1 if you find you've already got a value less than or equal to the value you've picked. You'd need to think about it carefully, but that's effectively the approach I'd look into.

提交回复
热议问题