AnyLogic中如何按距离排序集合内代理并使卡车优先前往最近点位
AnyLogic卡车优先配送最近点位实现方案
核心逻辑无需每次重排整个集合,只需提前存储待前往的目标点位,抵达后直接删除对应点位即可,具体实现步骤如下:
步骤1:新增存储目标点位的变量
在当前流程对应的代理(通常为卡车代理)中新增一个变量:
- 变量名:
currentTarget - 类型:点位集合
order.orderLocation存储的代理类型(例如自定义的Location类、Point类等) - 初始值:
null
步骤2:替换原有移动逻辑
把原来直接取集合第一个元素的moveTo代码替换为以下逻辑,自动筛选最近点位:
如果熟悉Java 8+的stream写法,可以用更简洁的版本:
// 筛选距离当前卡车最近的点位 currentTarget = order.orderLocation.stream() .min((loc1, loc2) -> Double.compare(distanceTo(loc1), distanceTo(loc2))) .orElse(null); if (currentTarget != null) { moveTo(currentTarget); }
如果不习惯stream写法,用普通循环实现效果完全一致:
double minDistance = Double.MAX_VALUE; currentTarget = null; // 遍历所有待配送点位找距离最近的 for (var location : order.orderLocation) { double currentDistance = distanceTo(location); if (currentDistance < minDistance) { minDistance = currentDistance; currentTarget = location; } } if (currentTarget != null) { moveTo(currentTarget); }
步骤3:抵达点位后删除对应目标
把原来删除集合首个元素的代码替换为以下逻辑,直接删除本次抵达的点位即可:
if (currentTarget != null) { order.orderLocation.remove(currentTarget); currentTarget = null; // 重置变量,方便下一轮循环筛选新的最近点位 }
如果你仍想通过排序集合实现
如果偏好先对集合排序再取首个元素的逻辑,之前排序失败大概率是比较规则设置错误,可以用以下代码实现排序:
// 按距离当前卡车的距离从小到大排序待配送点位集合 Collections.sort(order.orderLocation, (loc1, loc2) -> Double.compare(distanceTo(loc1), distanceTo(loc2))); // 排序后可以沿用你原来的逻辑,取第一个点位移动、删除 moveTo(order.orderLocation.getFirst()); // 抵达后执行 order.orderLocation.removeFirst();
原流程参考图:
内容的提问来源于stack exchange,提问作者Yope
相关产品推荐
相关产品推荐

