random number generator
Koroskin Denis
2korden at gmail.com
Wed Jul 30 12:36:00 PDT 2008
On Wed, 30 Jul 2008 23:28:14 +0400, Michael P. <baseball.mjp at gmail.com>
wrote:
> Okay. so I'm trying to make a simple Guess the Number game in D, and I
> need to know how to generate random number. (I'm pretty much done the
> other parts of the game)
> In C++, I would seed the random number generator with:
> srand( time( 0 ) );
> and the generate a random number from 1-10 with:
> randomnumber = ( rand() % 10 ) + 1;
>
> How would I go about doing the same thing in D?
> -Michael P.
First, srand() and rand() are C functions and thus are directly available
in D. Just import std.c.stdlib or tango.stdc.stdlib.
But if you use Tango, you should use tango.math.Random class instead. For
example,
// this will set random seed and return random value
uint randomValue = Random.shared.seed(someSeed /* optional */).next();
or in two steps:
Random.shared.seed( someSeed /* optional */ );
uint randomValue = Random.shared.next();
In Phobos, there is std.random module which has void rand_seed(int seed,
int index) and uint rand() methods.
More information about the Digitalmars-d-learn
mailing list