random number generator

Michael P. baseball.mjp at gmail.com
Wed Jul 30 12:41:10 PDT 2008


Koroskin Denis Wrote:

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

Thanks for fast reply. :P
Anyways, I tried importing the std.c.stdlib and the std.c.time to use those exact same functions, but I got errors trying to use time(0) as a argument. Forgot to mention I tried that.

So, what would I put as an argument for rand_seed instead of time(0)? Can I just put in any number? Like 0?
BTW, don't use Tango.

-Michael P.


More information about the Digitalmars-d-learn mailing list