Why do I get the same random number in 5000 calls?

Why do I get the same random number in this code?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <array>
#include <stdlib.h>
#include <time.h>

//Probability function should return an index according the probability value it contains.

int Probability(std::array<int,6> Probabilities)
{
	//To calculate probability:
	//Create a new array of size Probabilites.
	std::array<int,Probabilities.size()> Limits;

	//At each index of the array store total of all previous probabilites
	Limits[0] = 0;

	for(int i=1; i<Limits.size();i++)
	{
		Limits[i] = (Limits[i-1] + Probabilities[i]);
	} 

	//Get a random number.
	srand(time(NULL));
	int RandomNumber = rand()%100 + 1;
	std::cout<<"Random: "<<RandomNumber<<"\n";

	//find between which indexes the random number lies and return the lower one.
	for(int i=0;i<Limits.size() - 1;i++)
	{
		if(RandomNumber >= Limits[i] && RandomNumber< Limits[i+1])
			return i;
		continue;
	}
}

int main()
{
	const int			SPINS		  = 5000;
	std::array<char,6>	Characters = {'A','B','C','D','E','F'};
	std::array<int,6>	Probabilities = {10,5,2,38,25,20};
	std::array<int,6>	Frequencies = {0,0,0,0,0,0};
		
	for(int i=0;i<SPINS;i++)
	{
		Frequencies[Probability(Probabilities)]++;
	}

	for(int i=0;i<Frequencies.size();i++)
	{
		int Percentage = (Frequencies[i]/5000)*100;
		std::cout<<Characters[i]<<"\t"<<Percentage<<"%\n";
	}	
}

Last edited on
You must move srand out of your function into main function like that:

1
2
3
4
5
6
int main()
{
	std::srand(time(NULL));
        ///..... other code

}


This is becuase srand should be initialized only once and NOT every time you call the function.

because time(NULL) works on seconds thus giving you same number withing a second and diferent after each second has pased.

Which means you get different rand outcome every one second.

program executes your Probability function very fast, X times within a second giving you always same result within a second.
Last edited on
Thanks so much for that well explained answer :-)
Topic archived. No new replies allowed.