acota@pro-realm.cts.com (Arnold Cota) (09/23/90)
How do I generate a random number in the range of 1 to 54 in Lattice C? UUCP: crash!pro-realm!acota ARPA: crash!pro-realm!acota@nosc.mil INET: acota@pro-realm.cts.com
stelmack@screamer.csee.usf.edu (Gregory M. Stelmack) (09/23/90)
In article <4604@crash.cts.com> acota@pro-realm.cts.com (Arnold Cota) writes: >How do I generate a random number in the range of 1 to 54 in Lattice C? > I'll post here since my reply bounced, and others may be interested. srand(time(NULL)); /* seed random number generator */ int min,max; min = 1; max = 54; int x=0; x = rand()%max+min; See p. L168 of the Lattice manual. -- Greg Stelmack -- Email: stelmack@sol.csee.usf.edu -- USmail: USF Box 1510, Tampa, FL 33620-1510 -- Amiga: the only way to compute!
UH2@psuvm.psu.edu (Lee Sailer) (09/24/90)
In article <4604@crash.cts.com>, acota@pro-realm.cts.com (Arnold Cota) says: > >How do I generate a random number in the range of 1 to 54 in Lattice C? > Use one of the functions that generate a number in [0,1) (see the manual) multiply by 53 to get a number in [0,53.99999999), add one to get a number in [1.000000, 54.999999999) and assign the result to an integer to truncate. See a book such as Sedgewick's Algorithms for more detail. lee
thyssen@batserver.cs.uq.oz.au (Anthony Thyssen) (09/24/90)
acota@pro-realm.cts.com (Arnold Cota) writes: >How do I generate a random number in the range of 1 to 54 in Lattice C? I recently had the same problem as you - random numbers in a certian range To solve this I used the lattice C random number generators srand((long)time(NULL)); /* seed random with current time */ ULONG r = rand(); /* get a random number */ Note that the seeding is done once at the begining of your program only. the result is a number in the rand 0..2^31 IE a positive long number. (Of 31 bit length). I large number of people will then tell you to then mod (`%' in C) this over the range. - This is wrong and on larger ranges makes the random number generator tend to produce more low numbers in the range than higher ones. The solution is a little more complicated. The folloing is my macro definition to produce a number over a range (inclusive) #define RandInt(lo,hi) (int)\ ((lo)+((((long)((hi)-(lo)+1)*(long)(rand()&0x7fff))>>15) & 0x7fff)) Then to get a number over range 1 to 54 inclusive you do number = RandInt(1,54) The macro definition spreads the numbers produced equally over the whole range. Anthony Thyssen - (Dragon Computing!) thyssen@batserver.cs.uq.oz.au ------------------------------------------------------------------------------- It has been proved, beyond a shadow of a doubt, that million-to-one chances, occur nine times out of ten! --- Terry Pratchet -------------------------------------------------------------------------------