Mail Archives: djgpp/1998/01/18/18:30:21
Jeff W./DMT wrote:
>
> how do I get a random number from 0 to N in DJGPP? I tried looking
> up: random, srandom, and rand but none seem to help. SRand says it
> returns a number from 0 to RAND_MAX, and random returns a numbre from
> 0 to MAX_INT. Neither is what I'm looking for. Thanks for your help.
*sigh*. Using simple mathematical operations, you can convert a value
from 0 to RAND_MAX (or 0 to MAX_INT, since they are identical) into
whatever you want.
The simplest formula to get a value from 0 to N is "x = random( ) % N".
Some people will argue that this contributes to nonrandomness, so you'd
be better off taking the high order bits, but random(), as opposed to
rand() which uses an inferior algorithm, is a sufficiently good RNG that
modding will work.
Remember one other thing: you must seed the random number generator
with a value before using it. srand() seeds rand() and srandom() seeds
random() (the two are not interchangeable). A common value to use is
the internal clock, as in:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main( void )
{
int i;
srandom( (int) time( NULL ) );
for ( i = 0; i < 10; i++ )
printf( "%d ", random( ) % 100 + 1 );
printf( "\n" );
return 0;
}
--
---------------------------------------------------------------------
| John M. Aldrich | "It may be better to be a live jackal|
| aka Fighteer I | than a dead lion, but it is better |
| mailto:fighteer AT cs DOT com | still to be a live lion." |
| http://www.cs.com/fighteer | - Lazarus Long |
---------------------------------------------------------------------
- Raw text -