0

I have a function where I used srand(time(null)) and it worked fine, generating different numbers on each iteration. Then, I added a while inside my function, and now it generates the same two numbers during each iteration of the loop. Here is my code:

void readgraph()
{
    int i,vi=0,vj=0;
    for(i=0; i<nrVertices; i++)
        G[i]=NULL;

    for(i=0; i<nrVertices; i++)
    {
        srand(time(NULL));
        while(checkInsert(vi,vj)==false) //this is the while that I added
        {

            vi=rand()%nrVertices;
            vj=rand()%nrVertices;
            while(vj==vi)
            {
                vj=rand()%nrVertices;
            }
        }
        printf("%d %d\n",vi,vj);
        insert(vi,vj);
        insert(vj,vi);
    }
}

Any idea about how could I fix this? Thank you.

@milleniumbug my "short compilable code":

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define MAX 10000
#include <sys/time.h>

typedef struct node
{
    struct node *next;
    int vertex;
} node;
int a[10000][10000];
int nrVertices=100;
int nrEdges=1000;
node *G[10000];          //heads of the linked list
void readgraph()
{
    int i,vi=0,vj=0;
    for(i=0; i<nrVertices; i++)
        G[i]=NULL;
    for(i=0; i<nrEdges; i++)
    {
        while(checkInsert(vi,vj)==false)
        {

            vi=(rand()+i-2)%nrVertices;
            vj=(rand()+i+7)%nrVertices;
            while(vj==vi)
            {
                vj=rand()%nrVertices;
            }
        }
        printf("%d %d\n",vi,vj);
        //insert(vi,vj);
        //insert(vj,vi);
    }
}
int main()
{ 
    srand(time(NULL));
    readgraph();
    return 0;
}
Sportler
  • 9
  • 5

1 Answers1

0

You should run srand once - otherwise you're just reinitializing the state every time, which given you use time(NULL), the generated number changes only every next second and is completely predictable.

milleniumbug
  • 15,379
  • 3
  • 47
  • 71