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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more