mardi 26 mars 2019

Why is my C code only generating every third random number?

I am trying to simulate the propagation of a worm across a network made of 100,000 computers. The simulation itself is very simple and I don't need any help except that for some reason, I am only getting every third random number.

Only the computers whose index modulo 1000 is less than 10 can be infected so when 1000 computers are infected, the program should be done. For some reason, my program only gets 329. When I lower the goal number and check the contents of the array, only every third computer has been changed and it is a consistent pattern. For example at the end of the array, only computers 98001, 98004, 98007, 99002, 99005, 99008 are changed even though the computers in between (98002, 98003, etc.) should be changed as well. The pattern holds all the way to the beginning of the array. When I try to get all 1000 changed, the program goes into an infinite loop and is stuck at 329.


#define NETSIZE 100000

double rand01();
void initNetwork();

unsigned char network[NETSIZE];
int scanrate = 3;
int infectedCount;
int scans;
int ind;
int time;

initNetwork();
time = 0;
infectedCount = 1;

while (infectedCount < 1000) { //changing 1000 to 329 stops the infinite loop
    scans = infectedCount * scanrate;
    for (int j = 0; j < scans; j++) {
        ind = (int) (rand01() * NETSIZE);
        if (network[ind] == 0) {
            network[ind] = 1;
            infectedCount++;
        }
    }
    time++;
}

double rand01() {
    double temp;
    temp = (rand() + 0.1) / (RAND_MAX + 1.0); 
    return temp;
}

void initNetwork() {
    for (int i = 0; i < NETSIZE; i++) {
        if (i % 1000 < 10) {
            network[i] = 0;
        } else  {
            network[i] = 2;
        }
    }
    // Patient 0
    network[1000] = 1;
}

In the above code, I expect the code to run until the 1000 vulnerable indexes are changed from 0 to 1.




Aucun commentaire:

Enregistrer un commentaire