cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              // the value we are trying to compute:
var target = Math.PI;
// the alphabet of symbols our code can use:
var symbols = ["+", "-", "*", "/", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
//var symbols = [".", "*", "1", "2"];
// this determines how many values a gene can take on:
var gene_range = symbols.length;
// how many genes in a genome:
var gene_size = 10;
// how many candidates in a generation:
var pop_size = 40;
// the number of phenotypes a child can select from as its parent:
var nearby_size = 3;
// the chance of choosing the best candidate in the neighborhood
// (set to 1 for deterministic tournament selection)
var nearby_probability = 1;
// the base probability of mutations:
var gene_mutation_rate = 0.1;
// initialize:
var generation = 0;
// generate a random population:
var pop = [];
for (var i = 0; i < pop_size; i++) {
  var geno = [];
  for (var j = 0; j < gene_size; j++) {
    geno[j] = random(gene_range);
  }
  pop.push(geno);
}

function develop(geno) {
  // convert genotype into phenotype (a string of code)
  var pheno = ["return "];
  for (var i = 0; i < gene_size; i++) {
    pheno.push(symbols[geno[i]]);
  }
  return pheno.join("");
}

function geno_eval(geno) {
  // develop the genotype into a phenotype of code:
  var code = develop(geno);
  write(code);
  // store for later printing
  geno.code = code;
  // default fitness is zero (in case there is an error below)
  geno.fitness = 0;
  // put into try block because random code can cause errors!
  try {
    // create an executable function from the code
    var test = new Function(code);
    // run it
    var result = test();
    geno.result = result;
    // throw out unusable values (last case checks for NaN)
    if (result != Infinity && result != -Infinity && result == result) {
      // convert this into a fitness scale of 0..1
      geno.fitness = 1 / (1 + Math.abs(target - result));
    }
  } catch (e) {
    //	console.log(e);
  }
}

function update() {
  // evaluate each member of the gene pool:
  for (var i = 0; i < pop_size; i++) {
    geno_eval(pop[i]);
  }

  // sort by fitness:		
  pop.sort(function(a, b) {
    return b.fitness - a.fitness;
  });

  // show them:
  for (var i = 0; i < pop_size; i++) {
    write(generation, i, pop[i].fitness, pop[i].result, pop[i].code);
  }

  // make a new generation:
  var newpop = [];
  // always keep the best candidate so far:
  newpop[0] = pop[0];
  for (var i = 1; i < pop_size; i++) {
    var child = [];
    
    // pick a parent by tournament selection
    // simpler because the population is already sorted
    // so we can just sample it a few times
    // and pick the lowest index (i.e. highest fitness)
    var n = random(pop.length);
    for (var j=1; j<nearby_size; j++) {
      if (random() < nearby_probability) {
        n = Math.min(n, random(pop.length));
      }
    }
    var parent = pop[n];

    // no fitness-proportionate mutability for tournament selection
    var mutability = gene_mutation_rate;
    
    // copy or mutate genes:
    for (var j = 0; j < gene_size; j++) {
      // mutate?
      if (random() < mutability) {
        child[j] = random(gene_range);
      } else {
        // copy:
        child[j] = parent[j]
      }
    }
    
    // shuffle?
    if (random() < mutability) {
      shuffle(child);
    }

    // add to population:
    newpop[i] = child;
  }

  // replace:
  pop = newpop;
  generation++;
}


            
          
!
999px
Close

Asset uploading is a PRO feature.

As a PRO member, you can drag-and-drop upload files here to use as resources. Images, Libraries, JSON data... anything you want. You can even edit them anytime, like any other code on CodePen.

Go PRO

Loading ..................

Console