Published
Edited
Feb 14, 2022
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
let population = d3.range(populationSize).map(randomPhrase);
let scores = population.map(fitness);
let generations = 1;
let bestPhrase = "";
while (bestPhrase !== target) {
const normalised = scores.map(d3.scaleLinear().domain([0, target.length]).range([0, 1]));
const matingPool = normalised.flatMap((d, i) => d3.range(Math.round(d * 100)).fill(population[i]));
const parent = () => matingPool[d3.randomInt(matingPool.length)()];
population = population.map(d => crossOver(parent(), parent())).map(mutate);
scores = population.map(fitness);
bestPhrase = population[d3.maxIndex(scores)];

yield html`<p>
Best evolved phrase:
<h2>${ bestPhrase }</h2>
after ${ ++generations } generations of evolution.
</p>`;
}
}
Insert cell
Insert cell
function fitness(member) {
return d3.sum([...member], (d, i) => d === target[i]);
}
Insert cell
Insert cell
function crossOver(parent1, parent2) {
const swapPoint = d3.randomInt(target.length)();
const leftSide = parent1.substr(0, swapPoint);
const rightSide = parent2.substr(swapPoint, target.length - swapPoint);
const child = leftSide + rightSide;
return child;
}
Insert cell
Insert cell
function mutate(phrase) {
const doMutation = () => d3.randomInt(100)() < mutationRate;
return [...phrase].map(letter => doMutation() ? randomLetter() : letter).join("");
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more