I’m creating a machine that generates a shotgun with random components that effect the overall quality of the gun. I’m having a problem generating the random parts that will comprise the shotgun. There are 4 parts that have to be generated. When I created each of these functions, I tested them individually and they all work but when I try to put them together with the createChromo() function, the numbers are individually random. I should be getting results like 2131 and 1332, but I keep getting 1111 or 1112 or 2221 or 2222….Here is the code:
int generateButt()
{
srand(unsigned(time(NULL)));
int buttType = rand() % 3 + 1;
if(buttType == 1)
{
accuracy = rand() % ((5 - 2) + 2) / 10.0;
fireRate = fireRate - 0.3;
}
if(buttType == 2)
{
accuracy = rand() % ((8 + 5) + 5)/ 10.0;
fireRate = fireRate - 0.2;
}
if(buttType == 3)
{
accuracy = rand() % ((11 + 8) + 8) / 10.0;
fireRate = fireRate - 0.1;
}
return buttType;
}
int generateBarrel()
{
srand(unsigned(time(NULL)));
int barrelType = rand() % 3 + 1;
if(barrelType == 1)
{
range = rand() % (16 - 5) + 5;
power = power + 3;
}
if(barrelType == 2)
{
range = rand() % (21 - 16) + 16;
power = power + 1;
}
if(barrelType == 3)
{
range = rand() % (26 + 21) + 21;
power = power - 1;
}
return barrelType;
}
int generateBullet()
{
srand(unsigned(time(NULL)));
int bulletType = rand() % 3 + 1;
if(bulletType == 1)
{
power = rand() % (16 - 10) + 10;
range = range + 5;
}
if(bulletType == 2)
{
power = rand() % (26 - 16) + 16;
range = range + 1;
}
if(bulletType == 3)
{
power = rand() % (35 - 26) + 26;
range = range - 2;
}
return bulletType;
}
int generateAction()
{
srand(unsigned(time(NULL)));
int actionType = rand() % 2 + 1;
if(actionType == 1)
{
fireRate = 1.5;
accuracy = accuracy + 0.2;
}
if(actionType == 2)
{
fireRate = 2.0;
accuracy = accuracy - 0.1;
}
return actionType;
}
void createChromo(int a, int b, int c, int d)
{
cout <<a<<b<<c<<d<<"\n";
}
int main()
{
for(int i = 0; i < popSize; i++)
createChromo(generateButt(), generateBarrel(), generateBullet(), generateAction());
system("pause");
return 0;
}
You’re calling
srandeach time you call either function. Whatsranddoes is seed the generator for a new string of random numbers. You base that seed off of the current second, so if it’s called in the same second, the seed will be the same as last time, and thus the sequence of random numbers obtained fromrand()will be as well.Call
srand(time(NULL));once at the beginning of your program to just have one sequence, and keep using the next number in that one sequence instead of starting the same sequence over.If you have access to C++11, you might consider using the
<random>header as well.