Published
Edited
Apr 23, 2021
Insert cell
md`# Genetic Algorithm Experiments #2`
Insert cell
r = require("ramda")
Insert cell
selectRandomFromArray = (array) => array[Math.floor(Math.random() * array.length)]
Insert cell
class Organism {
constructor(DNA = "") {
this.sex =
(DNA === "forcedMale" && "male") ||
selectRandomFromArray(["male", "female"]);
this.DNA = DNA;
this.age = 0;
}

breed(mate) {
if (mate.sex !== this.sex) {
return new Organism(
// clumsy way to make allele dominant
((this.DNA === "forcedMale" || mate.DNA === "forcedMale") &&
"forcedMale") ||
""
);
}
}
}
Insert cell
organism = new Organism()
Insert cell
function breedPopulation(population) {
const [females, males] = r.pipe(
r.forEach((organism) => organism.age++),
r.filter((organism) => organism.age <= 5),
r.partition(r.propEq("sex", "female"))
)(population);

return females
.concat(males)
.concat(
females.map((female) => female.breed(selectRandomFromArray(males)))
);
}
Insert cell
unfetteredGrowth = {
let population = new Array(10).fill().map((x) => new Organism());
let populationByGeneration = [population.length];
for (let i = 0; i < 30; ++i) {
population = breedPopulation(population);
populationByGeneration.push(population.length);
}
return populationByGeneration;
}
Insert cell
vegalite = require("@observablehq/vega-lite")
Insert cell
vegalite({
data: {
values: unfetteredGrowth.map((populationSize, index) => ({
generation: index,
populationSize
}))
},
mark: "line",
autosize: "fit",
width: width,
encoding: {
x: {
field: "generation"
},
y: {
field: "populationSize",
type: "quantitative"
}
}
})
Insert cell
fetteredGrowth = {
let population = new Array(10).fill().map((x) => new Organism());
population[0].DNA = "forcedMale";
let populationByGeneration = [population.length];
for (let i = 0; i < 30; ++i) {
population = breedPopulation(population);
populationByGeneration.push(population.length);
}
return populationByGeneration;
}
Insert cell
vegalite({
data: {
values: fetteredGrowth.map((populationSize, index) => ({
generation: index,
populationSize
}))
},
mark: "line",
autosize: "fit",
width: width,
encoding: {
x: {
field: "generation"
},
y: {
field: "populationSize",
type: "quantitative"
}
}
})
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