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.
In reply to Pick k numbers at random by Chuma
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |