[Issue 7863] New: randomShuffle doesn't work with a Xorshift
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Sun Apr 8 17:11:10 PDT 2012
http://d.puremagic.com/issues/show_bug.cgi?id=7863
Summary: randomShuffle doesn't work with a Xorshift
Product: D
Version: D2
Platform: x86
OS/Version: Windows
Status: NEW
Keywords: rejects-valid
Severity: normal
Priority: P2
Component: Phobos
AssignedTo: nobody at puremagic.com
ReportedBy: bearophile_hugs at eml.cc
--- Comment #0 from bearophile_hugs at eml.cc 2012-04-08 17:11:51 PDT ---
D2 code:
import std.random: Xorshift, randomShuffle;
void main() {
Xorshift rndEng = Xorshift(1);
int[] a = [10, 20, 30, 40];
randomShuffle(a, rndEng);
}
DMD 2.058beta3 gives:
...\dmd2\src\phobos\std\random.d(1263): Error: cannot implicitly convert
expression (rndGen()) of type
MersenneTwisterEngine!(uint,32,624,397,31,-1727483681u,11,7,-1658038656u,15,-272236544u,18)
to XorshiftEngine!(uint,128,11,8,19)
test.d(5): Error: template instance
std.random.randomShuffle!(int[],XorshiftEngine!(uint,128,11,8,19)) error
instantiating
Currently randomShuffle is defined like this:
void randomShuffle(Range, RandomGen = Random)(Range r,
ref RandomGen gen = rndGen)
{
foreach (i; 0 .. r.length)
{
swapAt(r, i, i + uniform(0, r.length - i, gen));
}
}
I think this alternative definitions avoid the problem:
import std.random : uniform, Xorshift, rndGen;
import std.algorithm: swapAt;
/**
Shuffles elements of $(D r) using $(D gen) as a shuffler. $(D r) must be
a random-access range with length.
*/
void randomShuffle(Range)(Range r)
{
foreach (i; 0 .. r.length)
swapAt(r, i, i + uniform(0, r.length - i));
}
/// ditto
void randomShuffle(Range, UniformRandomNumberGenerator)(Range r,
ref UniformRandomNumberGenerator urng)
{
foreach (i; 0 .. r.length)
swapAt(r, i, i + uniform(0, r.length - i, urng));
}
void main() { // demo
Xorshift rndEng = Xorshift(1);
int[] a = [10, 20, 30, 40];
randomShuffle(a);
randomShuffle(a, rndEng);
}
See also Issue 4851
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list