Repository where I mostly put random python scripts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.4 KiB

  1. <html>
  2. <head>
  3. <script>
  4. class Gene
  5. {
  6. constructor(min, max, value)
  7. {
  8. this.min = min;
  9. this.max = max;
  10. this.value = value;
  11. }
  12. getRealValue()
  13. {
  14. return (this.max - this.min) * this.value + this.min;
  15. }
  16. getValue()
  17. {
  18. return this.value;
  19. }
  20. setValue(val)
  21. {
  22. this.value = val;
  23. }
  24. makeClone()
  25. {
  26. return new Gene(this.min, this.max, this.value);
  27. }
  28. }
  29. class Chromosome
  30. {
  31. constructor(geneArray)
  32. {
  33. this.genes = [];
  34. for(let i = 0; i < geneArray.length; i++)
  35. {
  36. this.genes.push(geneArray[i].makeClone());
  37. }
  38. }
  39. getGenes()
  40. {
  41. return this.genes;
  42. }
  43. mutate()
  44. {
  45. this.genes[Math.round(Math.random() * (this.genes.length-1))].setValue(Math.random());
  46. }
  47. }
  48. const mate = function(father, mother)
  49. {
  50. let son = new Chromosome(father.getGenes());
  51. let daughter = new Chromosome(mother.getGenes());
  52. for(let i = 0;i < son.getGenes().length; i++)
  53. {
  54. let blendCoef = Math.random();
  55. blendGene(son.getGenes()[i], daughter.getGenes()[i], blendCoef);
  56. }
  57. };
  58. const blendGene = function(gene1, gene2, blendCoef)
  59. {
  60. let value1 = (blendCoef * gene1.getValue()) +
  61. (gene2.getValue() * (1- blendCoef));
  62. let value2 = ((1-blendCoef) * gene1.getValue()) +
  63. (gene2.getValue() * blendCoef);
  64. gene1.setValue(value1);
  65. gene2.setValue(value2);
  66. };
  67. let gene1 = new Gene(1,10,.6);
  68. let gene2 = new Gene(2,5,0.4);
  69. let geneList = [gene1, gene2];
  70. var c = new Chromosome(geneList);
  71. var c2 = new Chromosome(c.getGenes());
  72. console.log(c.getGenes());
  73. console.log(c2.getGenes());
  74. c.mutate();
  75. c.mutate();
  76. console.log(c.getGenes());
  77. console.log(c2.getGenes());
  78. </script>
  79. </head>
  80. <body>
  81. </body>
  82. </html>