我必须使用Lists
在netlogo中执行一些操作。虽然我可以用它们完成简单的任务,但我还不够熟练,无法编写我当前的要求。
我有一个场景,其中海龟有变量Current-Age
和Previous-Age
。如果龟不符合某种threshold
,它们就会出生并死亡。
我想为每个补丁实现以下公式。
Best-list = (-1/Previous-Age) * (Distance between Patch & Turtle) for all the turtles
Best = Min [ Best-list]
我知道所涉及的步骤,但编码不成功。以下是步骤:
Best-List
公式的输出创建另一个列表Min
值,并将名称/ who of the turtle与最小值存储在名为Best-Turtle
这是我尝试但无效的代码。
set turtle-list (list turtles)
set turtle-age-list n-values length(turtle-list) [0]
set turtle-patch-dist-list n-values length(turtle-list) [0]
set best-list n-values length(turtle-list) [0]
ask patches[
foreach turtle-list(
set turtle-age-list replace-item ?1 turtle-age-list Previous-Age of turtles with [turtle= ?1]
)
]
由于上面的代码本身不正确,我无法继续执行下一步。
希望提前感谢您对代码的帮助。
此致
答案 0 :(得分:1)
首先,列表可能不是最简单的方法。但是,如果您出于某种原因必须使用列表,我认为您所要求的是可能的。我不完全确定你的意思是什么 - 你是否试图让每个补丁评估哪个乌龟是该补丁的最佳乌龟,并将该变量存储在全局列表中?我会假设这就是你的意思,但如果我误解了,我认为你可以根据自己的需要调整我的工作。
首先,传递给foreach
的任何列表必须具有相同的长度。因此,由于您的意思是每个补丁执行此操作,请确保每个补丁都调用列表创建过程,而不仅仅是检查列表。接下来,查看n-values
的字典 - 记者的语法意味着您需要使用您尝试接收的记者 - 使用n-values length(turtle-list) [0]
只会给出一个长度相同的零列表作为海龟的数量。
因此每个补丁都需要创建这些列表 - 确保为列表变量定义patches-own
,或者只使用let
来定义过程中的列表。你需要一个有序的海龟列表,它们以前的年龄,以及从调用程序的补丁到每只乌龟的距离。接下来,您可以创建一个根据公式生成值的列表。然后,您可以使用position
原语在公式生成的列表中查找最小值的位置,并使用该原语为 该值的索引。
它可能看起来像
to numerical
set best-turtle []
ask patches [
let turtle-list (sort turtles) ;;; list of sorted turtles
let turtle-prev-age-list n-values length(turtle-list) [ [i] -> [pre_age] of turtle i ] ;;; list of previous ages of turtles, in same order as above
let turtle-patch-dist n-values length(turtle-list) [ [i] -> distance turtle i ] ;;; list of distance from this patch to each turtle, in same order
set best-list n-values length(turtle-list) [ [i] -> ( ( -1 / ( item i turtle-prev-age-list ) ) * ( item i turtle-patch-dist ) ) ] ;;; list of calculated values for each turtle
let best-position position (min best-list) best-list ;;; gets the index of minimum value
set best-turtle lput item best-position turtle-list best-turtle ;;; adds the best turtle for this patch to the global list of best turtles
]
end
上述过程假设您的海龟有一个pre_age
变量,补丁有一个best-list
变量,每个补丁“最佳海龟”的列表都保存在全局变量best-turtle
中。从那里,您可以使用foreach
向列表中的海龟询问某些事情。请注意,如果乌龟的前一年龄为0,则会得到除以零的错误。
答案 1 :(得分:0)
turtles-own [age previous-age]
to-report evalfrom [_patch]
report (- distance _patch) / previous-age
end
to test
ca
crt 25 [
set age (10 + random 75)
set previous-age age - random 10
]
print min-one-of turtles [evalfrom (patch 0 0)]
end