You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在AnyLogic中生成符合条件的Agent索引列表

解决AnyLogic筛选Agent并获取索引列表的问题

要得到符合条件的Agent在种群中的索引编号列表,可以用以下两种可靠方法:

方法1:使用IntStream遍历索引(推荐)

这种方法直接遍历种群的索引范围,筛选对应索引的Agent是否满足条件,不会出现重复Agent导致的索引错误,更稳定:

// 导入必要的类(如果还没导入)
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.List;

// 筛选符合条件的Agent索引并收集为列表
List<Integer> filteredIndices = IntStream.range(0, main.facilities.size())
    .filter(i -> main.facilities.get(i).WasteAvlty == 1)
    .boxed()
    .collect(Collectors.toList());

// 格式化为你需要的{0,1,2,3}形式并输出
String output = "{" + String.join(",", filteredIndices.stream().map(String::valueOf).collect(Collectors.toList())) + "}";
traceln(output);

方法2:传统循环+indexOf(适用于Agent实例唯一的场景)

如果你的种群中每个Agent实例都是唯一的,也可以用循环遍历Agent,再通过indexOf获取索引:

import java.util.ArrayList;
import java.util.List;

List<Integer> indices = new ArrayList<>();
for (Facility p : main.facilities) {
    if (p.WasteAvlty == 1) {
        indices.add(main.facilities.indexOf(p));
    }
}

// 格式化输出
String output = "{" + String.join(",", indices.stream().map(String::valueOf).collect(Collectors.toList())) + "}";
traceln(output);

注意事项

  • 方法2中,如果种群存在重复的Agent实例(同一对象被多次添加),indexOf只会返回该实例第一次出现的索引,此时推荐用方法1。
  • 确保main.facilities是AnyLogic的Population或List类型,这两种都支持size()和get()方法。

内容的提问来源于stack exchange,提问作者Jahidul Hasan Razib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 22:03:11