Random Number Generation in a Loop

So, I've researched this quite a bit and the overwhelming answer I've been seeing for a loop generating the same pseudo-random number is that you're seeing the random number generator inside the loop, but that is not the case with me . . . At least not that I can see.

Basically, as I mentioned, I have a loop "birthing" new bunnies in a loop. And all the new bunnies are being created with the same name and other details.

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void BunnyGraduation::breed()
{
	for (unsigned int male = 0; male < colony.size(); male++)
	{
		if (colony.at(male).getSex() == Bunny::Sex::MALE && colony.at(male).getRadioactiveMutantVampireBunny() != true && colony.at(male).getAge() >= AGEOFCONSENT)
		{
			for (unsigned int female = 0; female < colony.size(); female++)
			{
				if (colony.at(female).getSex() == Bunny::Sex::FEMALE && colony.at(female).getRadioactiveMutantVampireBunny() != true && colony.at(female).getAge() >= AGEOFCONSENT)
				{
					birth(colony.at(female).getColor());
				}
			}
		}
	}
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
void BunnyGraduation::birth(Bunny::Color mothersColor)
{
	Bunny temporaryBunny;

	temporaryBunny.randomName();
	temporaryBunny.randomSex();
	temporaryBunny.setColor(mothersColor);
	temporaryBunny.setAge(0);
	temporaryBunny.randomMutantVampire();

	cout << endl << temporaryBunny.getName() << " was born!" << endl;

	colony.push_back(temporaryBunny);
}


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
void Bunny::randomSex()
{
	sex = static_cast<Bunny::Sex>(rand() % (int)Bunny::Sex::MAXIMUM);
}

void Bunny::randomColor()
{
	color = static_cast<Bunny::Color>(rand() % (int)Bunny::Color::MAXIMUM);
}

void Bunny::randomName()
{
	name = possibleNames[rand() % TOTALNAMES];
}

void Bunny::randomMutantVampire()
{
	const int OFFSET = 1;
	const int TOTAL = 11;

	const int RANDOMNUMBER = OFFSET + rand() % TOTAL;

	if (RANDOMNUMBER >= 1 && RANDOMNUMBER <= 2)
	{
		radioactiveMutantVampireBunny = true;
	}

	radioactiveMutantVampireBunny = false;

	
}


srand(time(0)); is seeded ONCE in the constructor of the bunny object itself. . . Now, come to think of it, the constructor is called every time an object is created . . . And the constructor contains the srand() . . . and the constructor is being called in a loop. . . So therefore, yes, the srand() is being called inside the loop.

BUT now the question becomes. . . How do I fix it?
Normally, srand is called just once, in the beginning of your main() function. Otherwise, because all the structs are created at about the same time (within the same second), the seed will be the same.
Omg, I'm so stupid. That makes sense. Totally fixed the issue.
Topic archived. No new replies allowed.