Skip to content

Commit fd98d4a

Browse files
committed
_
1 parent 67a60e1 commit fd98d4a

File tree

2 files changed

+33
-18
lines changed

2 files changed

+33
-18
lines changed

GeneticAlgorithm.php

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class GeneticAlgorithm
2323
public $parents = array();
2424
public $max_fitness = array();
2525

26-
public $crossover_rate = 0.25;
26+
public $crossover_rate = 0.35;
2727
public $mutation_rate = 0.1;
2828
public $population = 200;
2929
public $iteration = 0;
@@ -34,19 +34,19 @@ public function __construct()
3434
for ($i=0;$i<5;$i++)
3535
$this->chromosome[$i] = array(rand(0,10),rand(0,10),rand(0,10));
3636

37-
for ($i=0;$i<$this->population;$i++) {
38-
$this->selection();
39-
$this->crossOver();
40-
$this->mutation();
37+
// for ($i=0;$i<$this->population;$i++) {
38+
// $this->selection();
39+
// $this->crossOver();
40+
// $this->mutation();
4141

42-
for ($i=0;$i<5;$i++)
43-
if ($this->chromosome[$i][0] + 2 * $this->chromosome[$i][1] + 3 * $this->chromosome[$i][2] == 10)
44-
break;
42+
// for ($i=0;$i<5;$i++)
43+
// if ($this->chromosome[$i][0] + 2 * $this->chromosome[$i][1] + 3 * $this->chromosome[$i][2] == 10)
44+
// break;
4545

46-
$this->iteration++;
47-
}
46+
// $this->iteration++;
47+
// }
4848

49-
var_dump($this->chromosome);
49+
// var_dump($this->chromosome);
5050
}
5151

5252
public function calcFx(){
@@ -96,17 +96,31 @@ public function selection(){
9696
}
9797

9898
public function crossOver() {
99-
while($this->iteration < $this->population) {
100-
for($m=0; $m<4 ; $m++) {
99+
$count = 0;
100+
for($m=0; $m<5 ; $m++) {
101101
$random[$m]=mt_rand() / mt_getrandmax();
102102
if($random[$m] < $this->crossover_rate) {
103-
// $this->parents[$m] = $this->chromosome[$m];
104-
$ids = $m;
103+
$this->parents[$count] = $m;
104+
$count++;
105105
}
106106
}
107-
$cuts =
108-
$this->iteration += 1;
109-
}
107+
for($n = 0 ; $n<$count ; $n++) {
108+
$cut = rand(1,2);
109+
// echo $this->chromosome[$this->parents[$n]];
110+
for($p = 0; $p < $cut; $p++) {
111+
$newChromosome[$p] = $this->chromosome[$this->parents[$n]][$p];
112+
}
113+
for($t = $cut ;$t < count($this->chromosome[$this->parents[$n]]); $t++) {
114+
$u = $t + 1;
115+
if($u > $count) {
116+
$newChromosome[$t] = $this->chromosome[0][$t];
117+
}
118+
else
119+
$newChromosome[$t] = $this->chromosome[$this->parents[$u]][$t];
120+
}
121+
var_export($newChromosome);
122+
// $this->chromosome[$this->parents[$n]] = ??
123+
}
110124
}
111125

112126
public function mutation(){

index.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@
1212
require_once "GeneticAlgorithm.php";
1313

1414
$ga = new GeneticAlgorithm();
15+
echo $ga->crossOver();

0 commit comments

Comments
 (0)