NetLogo中的递归

问题描述 投票:1回答:1

在NetLogo 6.1.1中,我有一个品种(放牧者)正在寻找绿色补丁(灌木丛)中的另一个品种(咆哮)。

我无法获得的行为是这样:

  1. 如果发现了网罗,则以80%的成功率移除网罗;然后重复相同的过程(热点搜索;递归调用)。
  2. 如果没有发现网罗(20%的概率),则重复相同的步骤过程(热点搜索;注释掉的部分->导致无限循环)5次。

  3. 如果在这5次中都没有清除网罗,请恢复正常行为(随机向右转并前进1)。

我该怎么做?

;; globals =========================
breed [rangers ranger]
breed [snares snare]
rangers-own [snare-found?]

;; initialise ========================
to setup

  resize-world -4 4 -4 4

  clear-all

  create-rangers 1 [set color blue]

  ask patches [
    if random 100 < 20 [set pcolor green]]

  ask patches with [pcolor = green] [
    sprout-snares random 5]

  ask snares [
    set size 0.5 
    set shape "dot"
    fd 0.25
  ]

  reset-ticks

end

;; main ==================================
to go
  ask rangers [
    rt random 181 - 90
    fd 1
    if any? snares-here [hotspot-search]
    hotspot-search 
  ]

end

;; functions ===============================
to hotspot-search
  move-to patch-here
  let target one-of snares-here

  if (random 100 < 20) and (target != nobody) [
    ask target [die]
    set snare-found? true
    hotspot-search
  ]

  ;;if snare-found? = true [
  ;; repeat 5 [hotspot-search]
  ;;]

end
recursion netlogo
1个回答
0
投票

我想说的是,如果您希望护林员以20%的成功机会进行5次搜索,但是没有搜索成本,例如浪费时间或精力,您只需进行一次检查即可成功率为67%(1.00 - 0.80^5) = 0.67

但是如果您确实需要付费或需要跟踪搜索次数或类似的操作,以下是我编写代码的方式。很抱歉,从头开始编写而不是更新您的内容,我只是想让事情尽可能简单。

breed [ rangers ranger ]
breed [ snares snare ]

to setup
  create-snares 100 [
    set shape "circle"
    set color blue
    set size 0.5
    move-to one-of patches
  ]
  create-rangers 10 [
    set color red
    move-to one-of patches 
  ]
end

to go
  ask rangers [
    move-to one-of neighbors4
    ; call our procedure with the starting limit of 5
    hunt-snares 5
  ]
end

to hunt-snares [ search-limit ]
  ; the recursive base case is search-limit of 0
  if ( search-limit > 0 ) [
    ; can only find a snare if one exists here
    ifelse random 100 < 20 and any? snares-here [
      ; found one
      ifelse random 100 < 80 [
        ; disabled
        ask one-of snares-here [ die ]
        ; restart the search 
        hunt-snares 5 
      ] [
        ; we found a snare but failed to disable it, unclear what to do?
        hunt-snares 5
      ]
    ] [
      ; failed to find one, move towards the base case
      hunt-snares (search-limit - 1)
    ]
  ]
end

编辑添加:抱歉,我认为您的原始代码更复杂,实际上看起来相对简单,我可能应该修改您的版本。您的hotspot-search过程进入无限循环的原因是因为snare-found?从未在代码中的任何地方设置为false。处理递归的典型方法是使递归过程的一个参数进展为一个基本情况,在该情况下,最后一个递归调用可以退出,整个调用链也将结束。

在这种情况下,我们有两个并发症:1)不是参数的隐式基本情况-补丁上仍然存在圈套器以试图解除武装,以及2)我们可以将参数重置得离基本点更远情况,知道项目1意味着我们不会循环。

© www.soinside.com 2019 - 2024. All rights reserved.