Most efficient way of randomly choosing a set of distinct integers

后端 未结 8 714
囚心锁ツ
囚心锁ツ 2020-12-01 07:04

I\'m looking for the most efficient algorithm to randomly choose a set of n distinct integers, where all the integers are in some range [0..maxValue].

Constraints:<

相关标签:
8条回答
  • 2020-12-01 07:49

    Linear congruential generator modulo maxValue+1. I'm sure I've written this answer before, but I can't find it...

    0 讨论(0)
  • 2020-12-01 07:55

    One way to do it without generating the full array.

    Say I want a randomly selected subset of m items from a set {x1, ..., xn} where m <= n.

    Consider element x1. I add x1 to my subset with probability m/n.

    • If I do add x1 to my subset then I reduce my problem to selecting (m - 1) items from {x2, ..., xn}.
    • If I don't add x1 to my subset then I reduce my problem to selecting m items from {x2, ..., xn}.

    Lather, rinse, and repeat until m = 0.

    This algorithm is O(n) where n is the number of items I have to consider.

    I rather imagine there is an O(m) algorithm where at each step you consider how many elements to remove from the "front" of the set of possibilities, but I haven't convinced myself of a good solution and I have to do some work now!

    0 讨论(0)
提交回复
热议问题