Shuffle

Walter Bright newshound1 at digitalmars.com
Mon Jan 28 11:44:03 PST 2008


Frits van Bommel wrote:
> However, it's possible to implement a correct shuffle  [...]

std.random.randomShuffle() in Phobos 2.0 gets it right. The shuffle 
code can be replaced with:

version (D_Version2)
{
     auto rnd = Random(unpredictableSeed);
     randomShuffle(files, rnd);
}
else
{
     auto n = files.length;
     writefln(n, " music files");
     if (!n)
	return 0;

     /* Shuffle the files[] array using Durstenfeld's algorithm
      * based on the Fisher-Yates method
      */
     while (--n)
     {
	/* Pick random r in range 0..max, discarding others
	 * to eliminate modulo bias
	 */
	auto max = (typeof(std.random.rand()).max / (n + 1)) * (n + 1);
	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;
     }
}


More information about the Digitalmars-d-announce mailing list