As a starter I have no formal instruction in programming, my background is mathematics. While doing some browsing on the subject of generating x distinct random ints from 0 to y (with y>=x of course) I took a look in the FAQ and in Prelude's Corner about the subject. In the Prelude's Corner entry the second to last example (the part included here) really confuses me.
This (correct me if I'm wrong) generates a random int between 0 and n-1. Prelude states that the idea is to split the range of random function into buckets of equal size (Is this actually equal or just as near equal as is possible without adding extra code to worry about a few small values? by extreme example if RAND_MAX happened to be 2,would the one bucket be of length 1 and the other of length 2 to split the values 0,1,2 as evenly as possible?). Am I missing something when I think the following implementation of the nrand function is just as good but shorter and without the need for a loop:Code:int nrand ( int n ) { int r; int bucket_size = RAND_MAX / n; if ( n <= 0 || n > RAND_MAX ) return 0; do { r = std::rand() / bucket_size; } while ( r >= n ); return r; }
---Code:int nrand (int n) { if ( n <= 0 || n > RAND_MAX ) return 0; return (int)(((double)std::rand() * n) / ((double)RAND_MAX +1)); }
Thraen