<script language="JavaScript" type="text/JavaScript"> //<![CDATA[ var evolved = false; var genX; var genY; function Create() { genX = new Array(100); // Create an array of 100 creatures genY = new Array(100); // Create an array of 100 creatures for (i = 0; i < 100; ++i) // Go through the population { genX[i] = new Array(6); // Create 5 genes for each creature genY[i] = new Array(6); // Create 5 genes for each creature for (gene = 0; gene < 5; ++gene) // Go through each gene for each creature { genX[i][gene] = 0; // Assign each gene a starting value } } } function Mutate(gen) { for (i = 0; i < 100; ++i) // Go through the population { for (gene = 0; gene < 5; ++gene) // Go through each gene for each creature { if (Math.round(100*Math.random()) == 42) // Take a 1 in 100 shot { if (gen[i][gene] == 0) // Mutate this gene gen[i][gene] = 1 else gen[i][gene] = 0; } } } } function Maxfitness(gen) { var fitness; var maxfitness = 0; for (i = 0; i < 100; ++i) // Go through the population { fitness = 0; for (gene = 0; gene < 5; ++gene) // Go through each gene for each creature { if (gen[i][gene] == 1) { ++fitness; } } gen[i][5] = fitness; document.write(fitness); if (fitness > maxfitness) { maxfitness = fitness; if (maxfitness == 5) { evolved = true; } } } return(maxfitness); } function Reproduce(gen, nextgen) { var maxfitness = Maxfitness(gen); var k = 0; for (i = 0; i < 100; i++) { if (gen[i][5] == maxfitness) { for (gene = 0; gene < 5; gene++) { nextgen[k][gene] = gen[i][gene]; } k++; if (k == 100) { return; } for (gene = 0; gene < 5; gene++) { nextgen[k][gene] = gen[i][gene]; } k++; if (k == 100) { return; } } } for (i = 0; i < 100; i++) { if (gen[i][5] != maxfitness) { for (gene = 0; gene < 5; gene++) { nextgen[k][gene] = gen[i][gene]; } k++; if (k == 100) { return; } } } } function Run() { Create(); while (evolved == false) { Mutate(genX); Reproduce(genX, genY); document.write("<br />"); if (evolved == false) { Mutate(genY); Reproduce(genY, genX); } document.write("<br />"); } } Run(); //]]> </script>
Probability Demo Source
Subscribe to:
Posts (Atom)
No comments:
Post a Comment