我在PHP中有一个逻辑应用程序,用于确定订单的自动路由。为此,我们有一个路线和路线点矩阵,其中路线中的点可以在多个路线中。 所以,我们可以定义这样的路线:
Route1 = ['Depo','City 1','City 3','City 4']
Route2 = ['Depo','City 1','City 2','City 3', 'City 5']
Route3 = ['Depo','City 2','City4','City 5']
路线是固定的,路线上的点是从“Depo”仓库的最近点到最远点定义的 计划员从订单中选择必须交付的行,并且应用程序触发一个带有交付点的数组,如下所示:
['City 1','City 3','City 4','City 2', 'City 1', 'City 3', 'City 2', 'City 5','City 1']
问题:我怎样才能确定给定阵列的理想路线?我希望结果考虑到理想的路线是覆盖最多点的路线。 系统可以使用多个路由触发结果,在这种情况下,假设结果可能是路由1和路由2
如果有人需要更多细节,请发表评论 谢谢!
答案 0 :(得分:1)
如果我理解正确,路线中唯一的相关信息是他们访问的城市,而不是他们的订单。一个非常简单的实现就是这样的。请注意充足的优化空间:
$routes = [
'route1' => ['Depo', 'City 1', ...],
'route2' => ['Depo', 'City 2', ...],
...
];
$target = ['City 1','City 3','City 4','City 2', 'City 1', 'City 3', 'City 2', 'City 5','City 1'];
$target_point_count = array_count_values($target);
$best_route = null;
$best_score = 0;
foreach($routes as $route => $points) {
$route_score = 0;
foreach($points as $point) {
$route_score += intval($target_point_count[$point]);
}
if($route_score > $best_score) {
$best_route = $route;
$best_score = $route_score;
}
}
答案 1 :(得分:1)
此功能并不完美,但它可以作为构建自己算法的基础:
<?php
function determRoute(array $routes, $order)
{
// Because the same destination can occur multiple times we build a "factor" array.
$orderFactor = array_count_values($order);
$routeScores = array();
// We iterate over the routes
foreach ($routes as $key => $r) {
foreach ($orderFactor as $i => $f) {
// And if the destination exists in the route we add the factor
if (in_array($i, $r)) {
$routeScores[$key] = $routeScores[$key] + $f;
}
}
}
arsort($routeScores);
reset($routeScores);
// return the first array key with the highest score
return key($routeScores);
}
$routes['route1'] = ['Depo', 'City 1', 'City 3', 'City 4'];
$routes['route2'] = ['Depo', 'City 1', 'City 2', 'City 3', 'City 5'];
$routes['route3'] = ['Depo', 'City 2', 'City4', 'City 5'];
$order = ['City 1', 'City 3', 'City 4', 'City 2', 'City 1', 'City 3', 'City 2', 'City 5', 'City 1'];
while (0 !== count($order)) {
$resultRouteKey = determRoute($routes, $order);
$resultRouteKeys[] = $resultRouteKey;
$order = array_diff($order, $routes[$resultRouteKey]);
}
var_dump($resultRouteKeys);
/**
The output is:
array(2) {
[0] =>
string(6) "route2"
[1] =>
string(6) "route1"
}
*/