I'd probably start by creating a class that describes a population and has methods like Kill and Reproduce. The easiest way to implement this would probably be using a map of int (or you could create a structure that describes an animal, but since they only seem to have a number right now, creating a new class for that doesn't seem necessary). The key will be the random number, the value will be the number of animals having this value (this makes it easier to erase them later on).
1 2 3 4 5 6 7 8 9
|
class Population
{
private:
std::map<int,int> animals;
public:
Population(int initial);
void Kill();
void Reproduce();
};
|
First thing to do would be to create the constructor, which creates the initial animals by drawing random numbers from 1 to 36. This can be done using the rand function in <cstdlib>, or using a random number engine from the C++11 <random>. I chose to use rand here so you can compile it without C++11 support too. We use the random value as the key for the map and increase the value of that key by 1, that way we keep track of the number of animals having that id.
1 2 3 4 5 6 7 8
|
Population::Population(int initial)
{
for(int i = 0; i < initial; ++i)
{
int key = std::rand() % 36 + 1;
this->animals[key] += 1; //Increase the value
}
}
|
Next we implement the kill method, it should simply delete all keys which have a value larger than 1. We can do this using an iterator that iterates over the map, and deletes all elements with a value larger than 1.
1 2 3 4 5 6 7 8 9 10 11 12
|
void Population::Kill()
{
std::map<int,int>::iterator it = this->animals.begin();
std::map<int,int>::iterator end = this->animals.end();
while(it != end)
{
if(it->second > 1)
this->animals.erase(it++);
else
++it;
}
}
|
Last thing to do will be to create a reproduce method. If we always called kill before reproduce, we could simple check the map size and create that many new animals. But if I read your question correctly this might not always be the case. So we will have to manually count all the animals and create that many new ones.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void Population::Reproduce()
{
int sum = 0;
for(std::map<int,int>::iterator it = this->animals.end(); ++it)
{
sum += it->second;
}
for(int i = 0; i < sum; ++i)
{
int key = std::rand() % 36 + 1;
this->animals[key] += 1;
}
}
|
Using this class it shouldn't be that hard to implement the rest. All you have to do is create a simple loop that calls Kill and Reproduce on an instance of Population. Of course, if you will be using rand like I did here, don't forget to call srand at the start of your main function to seed the engine.