Skip to content

Instantly share code, notes, and snippets.

@hostilefork
Created November 25, 2012 16:01
Show Gist options
  • Save hostilefork/4144159 to your computer and use it in GitHub Desktop.
Save hostilefork/4144159 to your computer and use it in GitHub Desktop.
"Genetic Algorithm" from someone's StackOverflow question
// http://stackoverflow.com/questions/13552057/c-vector-access-violation-when-trying-to-write
#include <iostream>
#include <vector>
using namespace std;
class gen {
public:
int basa_biner;
};
class chromosome {
public:
int chromosome_id;
int fitness;
vector<gen*> gen_chromosome;
chromosome(int chromosome_length) :
gen_chromosome(chromosome_length)
{
for(int i=0;i<chromosome_length;i++) {
gen_chromosome[i] = new gen(); //gen_chromosome[i]->basa_biner = rand()%2;
}
}
int get_chromosome_size() {
return gen_chromosome.size();
}
};
class network {
public:
network(int number, int hidden) {}
void init_network(int hidden) {}
void feedforward(float* input) {}
int error_function(float* input) {}
void getweight(float* tempWeight) {}
};
class population {
private:
vector<chromosome*> chromosome_population;
vector<network*> gennet;
int population_number;
public:
population(int numberOfPopulation, float input[],
float desired_output[], int hiddenNeuronNumber)
: chromosome_population(numberOfPopulation)
, gennet(numberOfPopulation)
{
population_number = numberOfPopulation;
float tempWeight[1200];
int chromosome_length;
for(int i=0;i<population_number;i++)
{
chromosome_population[i] = new chromosome(1200);
gennet[i] = new network(3,hiddenNeuronNumber);
}
for(int i=0;i<population_number;i++)
{
chromosome_length = chromosome_population[i]->get_chromosome_size();
chromosome_population[i]->chromosome_id = i;
cout << "Population no : " <<
chromosome_population[i]->chromosome_id << endl;
gennet[i]->init_network(hiddenNeuronNumber);
gennet[i]->feedforward(input);
cout << "error : " <<
gennet[i]->error_function(desired_output) << endl;
gennet[i]->getweight(tempWeight);
for(int j=0;j<chromosome_length;j++)
{
chromosome_population[i]->fitness =
(1-gennet[i]->error_function(desired_output))*100;
chromosome_population[i]->gen_chromosome[j]->basa_biner =
tempWeight[j];
}
cout<<endl<<"fitness : "<<chromosome_population[i]->fitness<<endl;
}
cout<<endl;
cout<<"Population : ";
for(int i=0;i<population_number;i++)
{
chromosome_length = chromosome_population[i]->get_chromosome_size();
cout<<"Population no : "<<i<<" ";
for(int j=0;j<chromosome_length;j++)
{
cout << chromosome_population[i]->gen_chromosome[j]->basa_biner;
}
cout<<endl;
}
cout<<endl;
}
};
int main()
{
float input[200];
float output[200];
population(200,input,output,200);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment