Shuffle
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Sun Jan 27 06:06:29 PST 2008
Walter Bright wrote:
> Latest based on suggestions:
>
>
[snip start]
> /* Shuffle the files[] array using Durstenfeld's algorithm
> * based on the Fisher-Yates method
> */
> auto max = (typeof(std.random.rand()).max / n) * n;
> while (--n)
> {
> /* Pick random r in range 0..max, discarding others
> * to eliminate modulo bias
> */
> auto r = max;
> do
> r = std.random.rand();
> while (r >= max);
>
> auto j = r % (n + 1); // pick element to swap with
>
> // swap [n] and [j]
> auto tmp = files[n];
> files[n] = files[j];
> files[j] = tmp;
> }
[snip rest]
Wrong again. The calculationof "max" should be inside the loop, since it
depends on "n" which is different for each iteration.
More information about the Digitalmars-d-announce
mailing list