From c50a00b70e48a9de8a3740f214e04f7ae4ab60a6 Mon Sep 17 00:00:00 2001 From: Dennis Eichhorn Date: Tue, 31 Oct 2017 19:18:04 +0100 Subject: [PATCH] Bug fix and optimize tsp algo --- Math/Optimization/TSP/City.php | 4 ++-- Math/Optimization/TSP/GA.php | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Math/Optimization/TSP/City.php b/Math/Optimization/TSP/City.php index 3b27a6a88..5719f2cf7 100644 --- a/Math/Optimization/TSP/City.php +++ b/Math/Optimization/TSP/City.php @@ -61,7 +61,7 @@ class City * * @since 1.0.0 */ - public function __construct(float $lat, float $long, string $name) + public function __construct(float $lat = 0, float $long = 0, string $name = '') { $this->long = $long; $this->lat = $lat; @@ -107,7 +107,7 @@ class City } /** - * Distance to city + * Distance to city in meter * * @param City $city City * diff --git a/Math/Optimization/TSP/GA.php b/Math/Optimization/TSP/GA.php index cbf3169ca..9d284bb2f 100644 --- a/Math/Optimization/TSP/GA.php +++ b/Math/Optimization/TSP/GA.php @@ -94,9 +94,9 @@ class GA $newPopulation->set($i, $child); } - $count = $newPopulation->count(); + $count2 = $newPopulation->count(); - for ($i = $shift; $i < $count; $i++) { + for ($i = $shift; $i < $count2; $i++) { $this->mutate($newPopulation->get($i)); } @@ -115,7 +115,7 @@ class GA private function tournamentSelection(Population $population) : Tour { $tournament = new Population($this->cityPool, self::TOURNAMENT, false); - $populationSize = $population->count(); + $populationSize = $population->count() - 1; for ($i = 0; $i < self::TOURNAMENT; $i++) { $tournament->add($population->get(mt_rand(0, $populationSize))); @@ -138,8 +138,8 @@ class GA { $child = new Tour($this->cityPool, false); - $start = mt_rand(0, $tour1->count()); - $end = mt_rand(0, $tour1->count()); + $start = mt_rand(0, $tour1->count() - 1); + $end = mt_rand(0, $tour1->count() - 1); $count = $child->count(); /* $tour1->count() ???!!!! */ @@ -182,7 +182,7 @@ class GA for ($pos1 = 0; $pos1 < $count; $pos1++) { if (mt_rand(0, 1000) < self::MUTATION) { - $pos2 = mt_rand(0, $tour->count()); + $pos2 = mt_rand(0, $tour->count() - 1); /* Could be same pos! */ $city1 = $tour->getCity($pos1);