xxxxxxxxxx
104
let targetString = "hi";
let populationSize = 100;
let mutationRate = 0.01;
let population = [];
let bestStringP;
function setup() {
createCanvas(400, 400);
bestStringP = createP();
// Initialize the population with random DNA
for (let i = 0; i < populationSize; i++) {
let dna = generateRandomDNA(targetString.length);
let unit = {
dna: dna,
fitness: 0
};
population.push(unit);
}
}
function draw() {
background(220);
// Evaluate fitness for each unit
for (let unit of population) {
unit.fitness = calculateFitness(unit.dna);
}
// Find the unit with the highest fitness
let maxFitness = 0;
let bestUnit;
for (let unit of population) {
if (unit.fitness > maxFitness) {
maxFitness = unit.fitness;
bestUnit = unit;
}
}
// Check if the target string has been generated
if (bestUnit.dna === targetString) {
console.log("Target string found:", bestUnit.dna);
noLoop();
}
// Display the best string found so far
bestStringP.html("Best String Found: " + bestUnit.dna);
// Generate new population based on the best unit
let newPopulation = [];
for (let i = 0; i < populationSize; i++) {
let parent = selectParent(population);
let childDNA = mutateDNA(parent.dna);
let child = {
dna: childDNA,
fitness: 0
};
newPopulation.push(child);
}
// Replace the old population with the new one
population = newPopulation;
}
function generateRandomDNA(length) {
let dna = "";
for (let i = 0; i < length; i++) {
let charCode = random(32, 127); // Generate a random character code
let char = String.fromCharCode(charCode); // Convert to character
dna += char;
}
return dna;
}
function calculateFitness(dna) {
let fitness = 0;
for (let i = 0; i < targetString.length; i++) {
if (dna.charAt(i) === targetString.charAt(i)) {
fitness++;
}
}
return fitness;
}
function selectParent(population) {
let index = floor(random(population.length));
return population[index];
}
function mutateDNA(dna) {
let mutatedDNA = "";
for (let i = 0; i < dna.length; i++) {
if (random() < mutationRate) {
let charCode = random(32, 127);
let char = String.fromCharCode(charCode);
mutatedDNA += char;
} else {
mutatedDNA += dna.charAt(i);
}
}
return mutatedDNA;
}