Bug 7863 – randomShuffle doesn't work with a Xorshift

Status
RESOLVED
Resolution
DUPLICATE
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2012-04-08T17:11:00Z
Last change time
2013-07-16T02:32:30Z
Keywords
rejects-valid
Assigned to
nobody
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2012-04-08T17:11:51Z
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
Comment #1 by joseph.wakeling — 2013-07-02T10:00:43Z
Cf. my response to Issue #9607 -- there's a pull request under review that should fix this: http://d.puremagic.com/issues/show_bug.cgi?id=9607
Comment #2 by joseph.wakeling — 2013-07-16T02:32:30Z
Fixed by pull request: https://github.com/D-Programming-Language/phobos/commit/443b54e30b4b67b8968ecde51dcae66c855c135b See also: http://d.puremagic.com/issues/show_bug.cgi?id=9607 *** This issue has been marked as a duplicate of issue 9607 ***