random numbers

Hello, I wrote a recursive function and I don't know if it is the cause that the random naumers seems don't work. That is to say it works one time but as they are in a loop they expect to change more times
thanks

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
....
main method here
  for(int n=0; n<5; n++)
	{
		formula = setFormula(individuo, n);
	}
	cout << "formula:"<<formula<<endl;
	return 0;
}
	//Formula recursiva
string setFormula(vector<Individuo> ind, int n)
{
	unsigned int seed{0};
	srand(static_cast<unsigned int>(time(0)));
	int i = rand()%ind.size();	
	//int j = rand()%operacion.size();
	cout<<"i="<<i<<endl;
	if (n<=1)
	{
		return ind[i].getFactor();
	}
	else
	{
		return "("+ind[i].getFactor()+ind[i].getOperacion() + setFormula(ind,n-1)+")";
	}
Hello psosmol,

Line 13 is being done every time you enter the function. The seed only needs to be done once. This is generally done near the beginning of "main".

By putting "srand" in the function every time yo enter the function you create a new starting point. If by chance you use "srand" quick enough your seed number may not have changed thus producing the same number two or more times.

I do remember a post that says if using "Windows" follow "srand" with a call to "rand" before you actually use "rand" to get your random number for something. I have seen this method make a difference before.

It would also help if you post the whole code to see if there is any other problems.

Hope that helps,

Andy

Edit: type
Last edited on
Topic archived. No new replies allowed.