Skip to content

Instantly share code, notes, and snippets.

@Shikugawa
Created April 3, 2017 12:07
Show Gist options
  • Save Shikugawa/943aa1a77f42e8181ed4569b4fe28edc to your computer and use it in GitHub Desktop.
Save Shikugawa/943aa1a77f42e8181ed4569b4fe28edc to your computer and use it in GitHub Desktop.
GeneticAlgorithm.pde
class DNA{
float[] x = new float[1000];
float[] y = new float[1000];
DNA(){
for(int i = 0; i < x.length - 1; i++){
x[i+1] += x[i] > 0 ? random(-1, 1) : random(0, 1);
y[i+1] += y[i] > 0 ? random(-1, 1) : random(0, 1);
}
}
float fitness(){
return 100 * sqrt(pow(x[999], 2) + pow(y[999], 2)) / sqrt(500000);
}
}
DNA[] population = new DNA[100];
int TimesOfGenerationalChange = 0;
void setup(){
size(500, 500);
for(int i = 0; i < population.length; i++){
population[i] = new DNA();
}
for(int i = 0; i < population.length; i++){
if(population[i].fitness() != 100){
study();
TimesOfGenerationalChange++;
}else{
break;
}
}
}
void study(){
ArrayList<DNA> pool = new ArrayList<DNA>();
for(int i = 0; i < population.length; i++){
int n = int(population[i].fitness());
for(int j = 0; j < n; j++){
pool.add(population[i]);
}
}
for(int j = 0; j < population.length; j++){
int a = int(random(pool.size()));
int b = int(random(pool.size()));
population[j] = makechild(pool.get(a), pool.get(b));
}
}
DNA makechild(DNA parent1, DNA parent2){
DNA child = new DNA();
println("a");
for(int i = 0; i < child.x.length; i++){
child.x[i] = i < int(random(child.x.length)) ? parent1.x[i] : parent2.x[i];
child.y[i] = i < int(random(child.x.length)) ? parent1.y[i] : parent2.y[i];
}
println("b");
return child;
}
void draw(){
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment