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 Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

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
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console