首页 > 解决方案 > 在 Netlogo 中处理列表中的索引位置

问题描述

我正在使用这些变量来解决以下问题:

set variablex .5
set threshhold-list [0 .3 .6]
set variable-list [0 0 1]

我有三个代理类型 0,1,2 对应于阈值列表和变量列表的索引位置。所以代理 0 有阈值 0 和变量 0,代理 1 有阈值 0.3 和变量 0,代理 2 有阈值 0.6 和变量 1。

我想做的是检查是否有任何代理的阈值大于零且小于 variablex。如果是这样,请将变量列表中该代理的变量更新为 variablex。也就是说,对于上面的变量,我想运行产生一个新变量列表的逻辑,如下所示:

variable-list [0 .5 1]

但是如果 variablex 是 0.7,它将产生 [0 .7 .7]。

我有一些我一直在破解的代码,但我觉得它比问题更复杂,所以我想知道是否有人能指出我正确的方向。非常感谢!

标签: netlogo

解决方案


有几种不同的方法可以解决这个问题,但如果我遇到你的情况,我会先写一个小记者,给我应该存储在每个索引中的值:

to-report new-value [ i ]
  let t item i threshhold-list
  report ifelse-value (t > 0 and t < variablex)
    [ variablex ] ; the variable's new value should be variable x
    [ item i variable-list ] ; the variable's value should not change
end

一旦你有了它,你可以使用或者foreach改变map你的变量列表:

to update-variables-with-foreach  
  foreach range length variable-list [ i ->
    set variable-list replace-item i variable-list new-value i
  ]
end

to update-variables-with-map
  set variable-list map new-value range length variable-list
end

这是一个有点冗长的测试,用于检查两个版本是否会给您预期的结果:

globals [
  variablex
  threshhold-list
  variable-list
]

to test
  clear-all
  set threshhold-list [0 .3 .6]

  set variablex .5
  set variable-list [0 0 1]
  update-variables-with-foreach
  print variable-list

  set variablex .5
  set variable-list [0 0 1]
  update-variables-with-map
  print variable-list

  set variablex .7
  set variable-list [0 0 1]
  update-variables-with-foreach
  print variable-list

  set variablex .7
  set variable-list [0 0 1]
  update-variables-with-map
  print variable-list

end

话虽如此,尽管我认为玩列表很有趣,但我认为您正在以一种非常不网络化的方式解决您的问题。

NetLogo 的世界是海龟、补丁和链接的世界,而不是数组、索引和数字的世界。

您可以按照以下方式做一些事情:

globals [
  variable-x
]

turtles-own [
  threshhold
  variable
]

to setup
  clear-all
  set variable-x .5  
  (foreach [0 .3 .6] [0 0 1] [ [t v] ->
    create-turtles 1 [
      set threshhold t
      set variable v
    ]
  ])
  ask turtles [ update-variable ]
  ask turtles [ show variable ]
end

to update-variable ; turtle procedure
  if threshhold > 0 and threshhold < variable-x [
    set variable variable-x
  ]
end

我不知道你最终想要达到什么目标,但如果我能提供一般性建议,那就是尝试接受 NetLogo 的心态。每次你想在你的代码中使用某种索引时,退后一步再想一想:可能有更好的(如“more netlogoish”)方法来做到这一点。


推荐阅读