$foundPlaces = array(); foreach ($lines as $line) { $words = explode(" ", $line); $distances[$words[0]][$words[2]] = $words[4]; $distances[$words[2]][$words[0]] = $words[4]; if (!in_array($words[0], $foundPlaces)) { $foundPlaces[] = $words[0]; } if (!in_array($words[2], $foundPlaces)) { $foundPlaces[] = $words[2]; } } $allRoutes = getAllRoutes($foundPlaces); $minDistance = 10000; foreach ($allRoutes as $route) { $distance = calculateRouteDistance($route, $distances); if ($distance < $minDistance) { $minDistance = $distance; } } echo $minDistance; function getAllRoutes($places) { if (count($places) == 1) { return $places; } $allRoutes = array(); foreach ($places as $index => $place) { $newPlaces = $places; unset($newPlaces[$index]); $routes = getAllRoutes($newPlaces);
} else { foreach (newRoute(array_slice($points, 1)) as $route) { foreach (range(0, count($points) - 1) as $i) { (yield array_merge(array_slice($route, 0, $i), [$points[0]], array_slice($route, $i))); } } } } # should start and end at $point[0] (home), so remove and store that. # routes are then all the possible permutations of the remaining points # with home as the start and end point $home = array_shift($points); $start_time = microtime(true); $count = 0; # iterate over all possible routes foreach (newRoute($points) as $route) { # add start and end point array_unshift($route, $home); $route[] = $home; if ($distance = calculateRouteDistance($route)) { # update shortest distance if (!$shortestDistance or $distance < $shortestDistance) { $shortestDistance = $distance; $shortestRoute = $route; } } $count++; } printf("\nChecked %s routes in %s seconds.\n", number_format($count + 1), round(microtime(true) - $start_time, 2)); printf("Shortest route: %s\n", json_encode($shortestRoute)); printf("Distance: %s units\n\n", round($shortestDistance, 2));