[Issue 4851] Three suggestions for std.random

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Apr 16 12:58:11 PDT 2011


http://d.puremagic.com/issues/show_bug.cgi?id=4851



--- Comment #2 from bearophile_hugs at eml.cc 2011-04-16 12:54:38 PDT ---
That fourth idea is also useful to avoid a little trap. This code looks
correct, here randomCover() is used to act like the Python random.choice(), but
here it keeps taking the same value:

import std.stdio, std.random;
void main() {
    // can't be const
    /*const*/ int[] data = [1, 2, 3, 4];
    foreach (i; 0 .. 20) {
        int r = randomCover(data, rndGen).front;
        write(r, " ");
    }
}

Output:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1


The same bug can't happen with code like this, because the random generator is
not created inside the foreach scope:

import std.stdio, std.random;
void main() {
    // can't be const
    /*const*/ int[] data = [1, 2, 3, 4];
    foreach (i; 0 .. 20) {
        int r = randomCover(data).front;
        // int r = choice(data); // better
        write(r, " ");
    }
}

-- 
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