NetLogo技术问题:如何获取Link权重并计算指定路径总权重
解决思路与代码修正
我来帮你搞定这个计算路径总权重的问题!你的思路其实已经走对了——通过link-with获取相邻节点间的链接,接下来只要把每个链接的权重取出来累加就行。下面是具体的修正步骤和代码:
关键前提确认
首先得确保你的所有链接都有一个存储权重的变量(比如约定叫weight),如果还没定义,需要在代码开头的声明部分添加:
links-own [ weight ] ; 给所有链接添加weight属性,用来存储权重值
修改后的完整代码
to calculate-oldpath let oldList [ 25 0 1 2 3 4 9 8 7 6 5 10 11 12 13 14 19 18 17 16 15 20 21 22 23 24] let weighted-dist 0 foreach (but-last oldList) (but-first oldList) [ [a b] -> ask turtle a [ let node-link link-with turtle b ; 先检查链接是否存在,避免无链接时出错 if node-link != nobody [ ; 将当前链接的权重累加到总权重变量中 set weighted-dist weighted-dist + [weight] of node-link ] ] ] print (word "橙色路径总权重: " weighted-dist) end
代码细节解释
- 初始化总权重:
let weighted-dist 0先把总权重变量设为0,为后续累加做准备。 - 遍历相邻节点对:
foreach (but-last oldList) (but-first oldList)会依次取出列表中每一组相邻节点(比如25和0、0和1……23和24)。 - 获取链接并累加权重:
link-with turtle b能直接拿到海龟a和海龟b之间的链接;- 增加
if node-link != nobody的判断,是为了防止节点间没有链接时触发报错; [weight] of node-link取出该链接的权重值,直接加到总权重变量里。
- 输出结果:最后用
print输出计算好的橙色路径总权重。
这样就能准确算出你指定路径的总权重啦!
内容的提问来源于stack exchange,提问作者Alex Tan
相关产品推荐
相关产品推荐

