Published
Edited
Apr 21, 2022
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
sum = (...numbers) => numbers.reduce((a, b) => a + b, 0)
Insert cell
splitString = (str, point) => [str.substr(0, point), str.substr(point)]
Insert cell
randomInt = (min = 0, max = Number.MAX_SAFE_INTEGER) =>
min + Math.round(Math.random() * (max - min))
Insert cell
Insert cell
Insert cell
objects = [
{ object: "A", reward: 20, weight: 1 },
{ object: "B", reward: 5, weight: 2 },
{ object: "C", reward: 10, weight: 3 },
{ object: "D", reward: 40, weight: 8 },
{ object: "E", reward: 15, weight: 7 },
{ object: "F", reward: 25, weight: 4 },
{ object: "G", reward: 4, weight: 5 },
{ object: "H", reward: 7, weight: 2 }
]
Insert cell
Insert cell
carryProbability = 0.4
Insert cell
initialPopulation = Array(4)
.fill(null)
.map(
() =>
objects
.slice(0, -1)
.map((object) => (Math.random() <= carryProbability ? "1" : "0"))
.join("") + "1"
)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
fittestChromosomes = Object.entries(initialPopulationFitnessScores)
.sort(([a, a_score], [b, b_score]) => b_score - a_score)
.map(([chromosome, score]) => chromosome)
.slice(0, 2)
Insert cell
Insert cell
crossoverPoint = 4;
Insert cell
subChromosomes = fittestChromosomes.map((chromosome) =>
splitString(chromosome, crossoverPoint)
)
Insert cell
crossedPopulation = [
`${subChromosomes[0][0]}${subChromosomes[1][1]}`,
`${subChromosomes[1][0]}${subChromosomes[0][1]}`
]
Insert cell
Insert cell
mutationRate = 0.3
Insert cell
Insert cell
mutatedCrossedPopulation = crossedPopulation.map((chromosome) =>
mutate(chromosome)
)
Insert cell
mutatedPopulationScores = Object.fromEntries(
mutatedCrossedPopulation.map((chromosome) => [
chromosome,
getFitness(chromosome)
])
)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
createRandomChromosome = () =>
[...cities].sort(() => 0.5 - Math.random()).join("")
Insert cell
p2_initialPopulation = {
const population = [];

while (population.length < 4) {
const chromosome = createRandomChromosome();
const score = p2_getFitness(chromosome);

if (score < Number.POSITIVE_INFINITY) {
population.push(chromosome);
}
}

return population;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
p2_crossedPopulationScores = p2_crossedPopulation.map((chromosome) => [
chromosome,
p2_getFitness(chromosome)
])
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