Chuma has asked for the wisdom of the Perl Monks concerning the following question:
I have a fairly theoretical question today. I'd like to randomly pick k integers less than n. The numbers should be distinct, and all sets of numbers equally likely. What's an efficient way to do that?
I could for example make an array of the numbers less than n, choose a number at random, and then splice it from the array. But that's hardly the optimal way, since it would take O(n) time to make the array that I don't really need. Another way would be to pick a random number, check if it's been picked before, and if so try again. That would be good enough if k << n, but generally it's not great. Yet another option would be that if the picked number has been picked before, you just try the next number after; that would have a better worst-case time, but it would make some sets more likely than others.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Pick k numbers at random
by Athanasius (Archbishop) on Nov 12, 2019 at 13:06 UTC | |
|
Re: Pick k numbers at random
by haukex (Archbishop) on Nov 12, 2019 at 13:13 UTC | |
|
Re: Pick k numbers at random
by Chuma (Scribe) on Nov 12, 2019 at 14:09 UTC | |
by haukex (Archbishop) on Nov 12, 2019 at 15:20 UTC | |
by Discipulus (Canon) on Nov 12, 2019 at 20:48 UTC | |
by AnomalousMonk (Archbishop) on Nov 12, 2019 at 23:16 UTC | |
by syphilis (Archbishop) on Nov 13, 2019 at 01:06 UTC | |
| |
by ikegami (Patriarch) on Nov 14, 2019 at 18:19 UTC | |
by NERDVANA (Priest) on Nov 13, 2019 at 09:39 UTC | |
|
Re: Pick k numbers at random
by Anonymous Monk on Nov 13, 2019 at 00:13 UTC | |
by Anonymous Monk on Nov 15, 2019 at 18:00 UTC |