445,804 Members | 1,659 Online
Need help? Post your question and get tips & solutions from a community of 445,804 IT Pros & Developers. It's quick & easy.

# need suggestion about random selection

 P: n/a Hello. Problem: How can I select K random values from the elements 0,1,2,3,4...,N-1 ? I don't know if there's an easy way of doing this, but here are suggestions for doing it. One way is to select K random elements (using a rand()% N), and then see if any number was choosen twice, and then re-select the duplicats until the choosen numbers are distinct. That ought to work fine when K much smaller than N. But I guess it will be more problematic when K is about N/2. (when K>N/2, just select the numbers that are not selected). Another foolproof method (but probably very error prone when coding) is to select one element, then generate a rand()% (N-1) and select the number that is that many steps away from the last selected number (wrapping back to 0 when reaching past N-1. Fine, you have two numbers, then select the number that is rand()%(N-2) steps away, avoiding the already taken numbers, and so on.... that way you will never get a number twice! The problem is implementing it.. The third option is to use a vector and removing each choosen number, but is that really efficient? Do you have any clever idea for how to do this? Jul 22 '05 #1