Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $parent1 = array(1, 5, 7, 3, 6, 4, 2);
- $parent2 = array(1, 6, 2, 4, 3, 5, 7);
- $child = array_fill(0, count($parent1), null);
- //Αρχικοποίηση
- $bestValue = $parent1[0];
- $x = $parent1[1];
- $y = $parent2[1];
- $child[0]=$parent1[0];
- for ($i = 1, $len = count($parent1); $i < $len; $i++) {
- //Καλύτερη τιμή
- if ($x != $y) {
- $value1 = distanceTo($bestValue,$x) + checkMin($x,$child,$len);
- $value2 = distanceTo($bestValue,$y) + checkMin($y,$child,$len);
- if ($value1 < $value2 ) {
- $bestValue = $x;
- }
- else {
- $bestValue = $y;
- }
- }
- else {
- $bestValue = $x;
- }
- //Επόμενη γονίδιο
- $x = checkNext($bestValue ,$parent1,$child);
- $y = checkNext($bestValue ,$parent2,$child);
- //Καλύτερο γονίδιο στον απόγονο
- $child[$i] = $bestValue;
- }
- echo 'Απόσταση πρώτου γονέα: '.totalDistance($parent1).'<br>';
- echo 'Απόσταση δεύτερου γονέα: '.totalDistance($parent2).'<br>';
- echo 'Απόσταση απογόνου: '.totalDistance($child).'<br>';
- echo 'Απόγονος: ';
- print_r ($child);
- function checkMin($x,$child,$len) {
- $min = INF;
- for ($i = 0; $i < $len; $i++) {
- if (in_array($i,$child) === false) {
- $min = $min > distanceTo($x,$i) ? distanceTo($x,$i) : $min;
- }
- }
- return $min;
- }
- function checkNext($z, $parent, &$child) {
- $flag = 0;
- $position = 0;
- $x = array_search($z,$parent);
- for ($i = $x, $len = count($parent)-1; $i < $len ; $i++) {
- if (in_array($parent[$i+1],$child) === false) {
- $flag = 1;
- $position = $parent[$i+1] ;
- break;
- }
- }
- if ($flag === 0) {
- for ($i = 0, $len = count($parent)-1; $i < $len ; $i++) {
- if (in_array($parent[$i],$child) === false) {
- $position = $parent[$i];
- break;
- }
- }
- }
- return $position;
- }
- function distanceTo($x,$y) {
- $dis = array (
- array(999,75,99,9,35,63,8),
- array(51,999,86,46,88,29,20),
- array(100,5,999,16,28,35,28),
- array(20,45,11,999,59,53,49),
- array(86,63,33,65,999,76,72),
- array(36,53,89,31,21,999,52),
- array(58,31,43,67,52,60,999)
- );
- return $dis[$x-1][$y-1];
- }
- function totalDistance($x) {
- $d=0;
- for ($i=0; $i<count($x)-1 ;$i++) {
- $d+=distanceTo($x[$i],$x[$i+1]);
- }
- $d+=distanceTo($x[$i],$x[0]);
- return $d;
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment