-2

For a small program I am running I am using the rand() function to provide numbers for an array of 23 integers. I found that every time I run the code, it reuses the same numbers that were used before in the array, so i'm never getting different results each iteration. How can I fix this problem?

Edit: The code is and experiment of the birthday paradox. This paradox states that the chance that you would share a birthday with anyone in a room filled with 23 people is 50%, but naturally most people would think its quite smaller than that.

#include "stdio.h"
#include "stdlib.h"

#define interations 10 //number of repitition in the code for a more accurate percentage
#define numppl 23 //number of people

int main()
{
    int inv;
    float percent = 0, sum = 0;
    int i, j, k;
    int seq[numppl];

    for (inv = 0; inv < interations; inv++)
    {
        for (i = 0; i < numppl; i++) {
            seq[i] = rand() % 365;  //creates a random array of 'numppl' integers every iteration
        }

        for (j = 0; j < numppl; j++)
        {
            for (k = j + 1; k < numppl; k++)
            {
                if (seq[j] == seq[k]) //if any two number in the array match each other, increment sum by 1 
                    sum++;
            }
        }
    }

    percent = (sum / interations) * 100; //divide the amount of arrays with numbers that match with the number of total arrays generated for a percentage

    printf("Chance of two people sharing the same birthday is %f percent", percent);
}

Each iteration is a different array of random numbers, but when I run the code again, the arrays are the same as before, so I get the same percentage

Invisible Hippo
  • 124
  • 1
  • 1
  • 9
  • 4
    You need to show us the code you have written to do this. We can't help you unless we know what you've done. – Sterls Jun 05 '16 at 06:19

1 Answers1

1

That is the expected behavoiur of rand(). You need to seed the random number generator with srand().

Yağmur Oymak
  • 467
  • 4
  • 13