Created
February 26, 2025 12:18
-
-
Save omayib/0df848495eabe550ec64f71a3095cdee to your computer and use it in GitHub Desktop.
tebak kata dengan algoritma genetika
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function randomChar() { | |
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; | |
return chars.charAt(Math.floor(Math.random() * chars.length)); | |
} | |
function randomString(length) { | |
return Array.from({ length }, randomChar).join(''); | |
} | |
function calculateFitness(target, candidate) { | |
let score = 0; | |
for (let i = 0; i < target.length; i++) { | |
if (target[i] === candidate[i]) { | |
score++; | |
} | |
} | |
return score / target.length; | |
} | |
function crossover(parent1, parent2) { | |
let midpoint = Math.floor(Math.random() * parent1.length); | |
return parent1.slice(0, midpoint) + parent2.slice(midpoint); | |
} | |
function mutate(str, mutationRate = 0.1) { | |
return str.split('').map(char => (Math.random() < mutationRate ? randomChar() : char)).join(''); | |
} | |
function geneticAlgorithm(target, populationSize = 100, mutationRate = 0.1) { | |
let population = Array.from({ length: populationSize }, () => randomString(target.length)); | |
let generation = 0; | |
while (true) { | |
generation++; | |
// Calculate fitness for each candidate | |
let scoredPopulation = population.map(candidate => ({ | |
candidate, | |
fitness: calculateFitness(target, candidate) | |
})); | |
// Sort by fitness (higher first) | |
scoredPopulation.sort((a, b) => b.fitness - a.fitness); | |
console.log(`scoredPopulation ${JSON.stringify(scoredPopulation)}`); | |
// If we found the target, return the result | |
if (scoredPopulation[0].candidate === target) { | |
console.log(`Found: "${target}" in ${generation} generations!`); | |
return; | |
} | |
// Select the top 50% of the population to be parents | |
let parents = scoredPopulation.slice(0, populationSize / 2).map(p => p.candidate); | |
console.log(`Parents ${parents}`); | |
// Create a new population via crossover and mutation | |
population = []; | |
while (population.length < populationSize) { | |
let parent1 = parents[Math.floor(Math.random() * parents.length)]; | |
let parent2 = parents[Math.floor(Math.random() * parents.length)]; | |
let child = crossover(parent1, parent2); | |
let childMutate = mutate(child, mutationRate); | |
console.log(`Generation ${generation}, Parent1 : ${parent1}, Parent2: ${parent2}, Child: ${child}, Mutate: ${childMutate}`); | |
population.push(childMutate); | |
} | |
// console.log(`Generation ${generation}: ${scoredPopulation[0].candidate}, fitness:${scoredPopulation[0].fitness}`); | |
} | |
} | |
geneticAlgorithm("INFORMATIKA"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment