TIP: Click on subject to list as thread! ANSI
echo: os2prog
to: Sean Price
from: Mike Bilow
date: 1996-05-16 05:03:46
subject: Random Seed

Sean Price wrote in a message to all:

 SP>         Does anyone have code for a random seed that'll make a 
 SP> program generate a different random number each time it's run?  
 SP> Something that uses a system timer would probably work best.  I 
 SP> wrote a bitmap changer a long time ago and have been cleaning 
 SP> it up and adding some features so I can release it as freeware. 
 SP>  I'm using Watcom v.10.0 and the closest thing I could find to 
 SP> what I'm looking for is the clock() function, but this is ticks 
 SP> since the program's start which will be almost identical each 
 SP> time the program is run. 

There are several traditional ways to get a random seed.  The simplest by
far, assuming you are not looking for cryptographic levels of security, is
to get the system time and apply a hash function to it.  This is not
acceptable for cryptographic applications because anyone knowing the
approximate time the seed was generated and the hash algorithm could
reproduce the seed.

Bryan Flamig's excellent book "Practical Algorithms in C++" (ISBN
0-471-00955-5) discusses both hash algorithms and random number generators
in some detail.  The trick to using the system time to generate the seed is
to run it through a hash function that produces a uniformly distributed
result, since the system time is certainly not well distributed or random
looking.  Flamig suggests the ELF Hash algorithm used in Unix, and it is a
good suggestion since it is the most well respected non-cryptographic hash
I know:

   unsigned long ElfHash(const char *k) {
      unsigned long h = 0;
      while (*k) {
         h = (h << 4) + *((unsigned char *)k)++;
         unsigned long g = h & 0xF0000000L;
         if (g) h ^= g >> 24;
         h &= ~g;
      }
      return h;
   }

The ELF Hash takes as an argument a pointer to a NUL-terminated array of
bytes.  It would be trivial to modify the function to always process the
four bytes returned as the system time from the C time() function.  The
hash produces a 32-bit result which can be collapsed by any prime modulus
if needed.
 
-- Mike


--- 
* Origin: N1BEE BBS +1 401 944 8498 V.34/V.FC/V.32bis/HST16.8 (1:323/107)
SEEN-BY: 50/99 270/101 620/243 711/401 409 410 413 430 808 934 955 712/407
SEEN-BY: 712/515 517 628 713/888 800/1
@PATH: 323/107 396/1 270/101 712/515 711/808 934

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.