srand in D
Ali Çehreli
acehreli at yahoo.com
Sat Jan 8 23:34:17 UTC 2022
On 1/8/22 12:27 PM, kdevel wrote:
> On Sunday, 31 October 2021 at 17:02:00 UTC, Ali Çehreli wrote:
>> Just comment that line out. :) D's pseudo-random generators start
>> randomized by default:
>
> [...]
>
>> https://dlang.org/phobos/std_random.html
>
> Klicking at "Run" always delivers "mango":
>
> https://dlang.org/phobos/std_random.html#uniform
>
> A very unbalanced die
That example wrapped in a program is the following:
import std.stdio;
import std.random;
void main() {
auto rnd = MinstdRand0(42);
writeln(rnd.uniform!ubyte); // 102
writeln(rnd.uniform!ulong); // 4838462006927449017
enum Fruit { apple, mango, pear }
version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147
writeln(rnd.uniform!Fruit); // Fruit.mango
}
Apparently, the programmer wanted uniformly distributed randomness that
is reproducible. That's why they use a generator that is seeded with 42
there.
It does produce random results but the first Fruit happens to be "mango"
with that seed.
TIL, I can use uniform with a type as in uniform!Fruit. Pretty cool. :)
Ali
More information about the Digitalmars-d-learn
mailing list