www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/02/05/19:20:07

From: myknees AT aol DOT com (Myknees)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Easy random things.
Date: 6 Feb 1998 00:06:57 GMT
Lines: 50
Message-ID: <19980206000601.TAA03174@ladder03.news.aol.com>
NNTP-Posting-Host: ladder03.news.aol.com
References: <6bbs76$3v0$4 AT news DOT ox DOT ac DOT uk>
Organization: AOL http://www.aol.com
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

> My suggested solution is to grab a value from `time' on
> startup, and
> store it in a static or global variable.  On each call
> to randomize,
> increment this variable when using its value; this
> ensures that you
> use a different seed each time.  Okay, they're fairly
> predictable, but
> that shouldn't matter too much.

There was just a thread (or two) about this.  A couple gurus said that you
should just initialize the function once by calling srand(), if you initialize
it with srand().  I wrote a little program that shows the difference between
seeding once and seeding multiple times.  It is set up for a 43-line display. 
You hit a key to iterate the loop (if you chose to reseed each time you'll only
see a change if the time has changed.)  After hitting lots of keys you can see
that if you call srand() each time it is not random at all.

#include        <conio.h>
#include        <stdlib.h>
#include        <time.h>
#define         NBR_ROWS        43
#define         NBR_COLS        80

int main(void)
{
    int theRandNo, rowPosition, colPosition;
    char c;
        
    cprintf("Would you like to seed the function\n\r1) At the"
            "beginning of the program\n\r");
    cprintf("2) At each loop\n\r");
    c = getch();
    
    cprintf("Hit lowercase 'x' to exit.\n\r");
    if(c != '2')
      srand(time(0));
    
    while(getch()!='x'){
      if(c == '2')
        srand(time(0));
      theRandNo = rand();
      rowPosition = theRandNo % NBR_ROWS + 1;
      colPosition = theRandNo % NBR_COLS + 1;
      gotoxy(colPosition, rowPosition);
      cprintf("%d, %d", colPosition, rowPosition);      
    }
    return 0;
}

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019