[Issue 5849] std.random.dice is better as a range

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Aug 31 17:44:27 PDT 2013


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



--- Comment #7 from bearophile_hugs at eml.cc 2013-08-31 17:44:25 PDT ---
If we don't want to break the API of dice() making it a range, a simple
solution is to call the dice range "diceRange" and keep both (but perhaps dice
becomes a small function that returns diceRange.front).

Another interesting suggestion: in my code I've seen that most times I want to
use a dice/diceRange I have to map its result on the items of an array:


import std.stdio, std.random;
void main() {
    immutable probabilities = [0.2, 0.6, 0.1, 0.1];
    immutable values = "ACGT";
    foreach (_; 0 .. 10)
        values[probabilities.dice].write;
}


That outputs something similar to:
CGCCAAACCC


So an improvement for diceRange() is to accept as first argument the range of
probabilities, and as second optional argument a range of items. If the second
argument is not given, then it generates integers as dice(). If the second
argument is given, then it yields the items, according to their probabilities.
So that program becomes:


import std.stdio, std.random, std.range;
void main() {
    immutable probabilities = [0.2, 0.6, 0.1, 0.1];
    immutable values = "ACGT";
    probabilities.diceRange(values).take(10).writeln;
}


This is quite handy.

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