From: "John M. Aldrich" Newsgroups: comp.os.msdos.djgpp Subject: Re: random numbers? Date: Sun, 18 Jan 1998 18:23:16 -0500 Organization: Two pounds of chaos and a pinch of salt. Lines: 45 Message-ID: <34C28EE4.4479@cs.com> References: <34c2863d DOT 422495 AT news DOT ziplink DOT net> NNTP-Posting-Host: ppp241.cs.com Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk 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 #include #include 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 | ---------------------------------------------------------------------