randomShuffle
    Diggory 
    diggsey at googlemail.com
       
    Mon Jun  3 04:29:07 PDT 2013
    
    
  
On Monday, 3 June 2013 at 10:10:15 UTC, Yann wrote:
> Thanks a lot for the suggestions!
>
> Cheers,
> Yann
>
> On Monday, 3 June 2013 at 10:06:30 UTC, bearophile wrote:
>> Yann:
>>
>>> Is there a better way to accomplish this? Naively, I would 
>>> expect something like
>>> "return iota(1, 1000).randomShuffle.take(10).sort;"
>>
>> Two ways, the first gives items in random order, the second 
>> ordered as you seem to desire:
>>
>> import std.stdio, std.random, std.range, std.array;
>> void main() {
>>    iota(1, 1001).randomCover(rndGen).take(10).writeln;
>>    iota(1, 1001).randomSample(10).writeln;
>> }
>>
>>
>> But be careful with randomCover, because maybe it takes the 
>> rnd generator by value.
>>
>> Bye,
>> bearophile
For small samples from very large ranges an efficient algorithm 
would be:
int[] randomGen(int N, int M) {
     if (N == 0)
         return [];
     int[] result = randomGen(N-1, M-1);
     int num = rand(M);
     foreach (ref int i; result)
         if (i >= num)
             ++i;
     result ~= num;
     return result;
}
    
    
More information about the Digitalmars-d-learn
mailing list