This should generate randomized encodings of "1"s and "0"s in a string, correct?
This is called in the constructor of a Gene.
Eight Genes in an array are constructed per Chromosome.
A Population has a vector of Chromosomes.
Is there any point in that that could possibly lead to all of my chromosomes in the population having the same exact encoding? I'm giving genetic algorithms a shot, here, but I'm running into a ton of errors. (another one is that it segfaults when calculating which chromosomes get to mate, but that's another story)
I created friend functions with ostream for all my classes in order to check out the contents of each gene by passing the population to cout, and every single chromosome has an identical set of genes...
I'll try examining my code some more if I can find the problem.
It seems like when I call vector::resize(int) the population ends up copy constructing based on the first chromosome it constructed to put into the vector. Is there anything I can do about this?
Chromosome::Chromosome()
: value_(0), fitnessScore_(0), matingChance_(0)
{
for (int i=0; i<CHROMOSOME_MAX_LEN; i++)
data_[i].RandomizeBits();
CalculateScore();
DetermineFitness();
}
class Population
{
/* Unimportant details omitted */
// Contains all chromosomes.
vector<Chromosome> population_;
};
Population::Population(int numChromosomes)
{
while (numChromosomes < 0)
{
cout << "Error: Please enter positive number." << endl;
cin >> numChromosomes;
}
population_.resize(numChromosomes);
/* unimportant */
}
Unless I misunderstand, the vector will hold one Chromosome object when it's first created, and will construct this using the default ctor. For some reason, it decides to use the copy ctor on this first object when I call vector::resize().
Looking at vector::resize(), it takes a second (defaultable) parameter that of the contained type that you wish to put into the resized parts. That is then copied into the vector.
Hence, when you do resize, it expands and calls the constructors as expected, HOWEVER it then overwrites that data with the second parameter of the function.
Hope I explained that well enough...
Also, I was looking at your code and noticed your remove(...);
lines.
For one thing, data is a zero-length vector when lines 4-5 run, thus accessing the Nth element of the vector is a memory stomp. vector::operator[] does not create elements that don't exist.