将每个数字分配给3只乌龟

时间:2014-12-04 18:50:02

标签: netlogo

我正在创建一个程序,在1500个“学科”的世界中创造1,500名“科学家”(海龟)。

我需要将每只海龟分配一个“纪律”作为1-500之间的数字,并确保每个学科有3只海龟。

这意味着set(random)不合适。我可以使用原始语言吗?

没关系,我想我已经弄明白了。这有意义吗?

  to set-discipline
    ask turtles [ set discipline -1 ]
    let unassigned turtles
    let current 1
    while [any? unassigned]
    [
      ask n-of (min (list group-size (count unassigned))) unassigned
        [ set discipline current ]
      set current current + 1
      set unassigned unassigned with [discipline = -1]
    ]
  end

2 个答案:

答案 0 :(得分:1)

您的代码有效,但非常...非网络。 NetLogo中的while循环和索引通常表明您没有充分利用该语言的功能。至少,我会将while替换为foreach

ask turtles [ set discipline -1 ]
foreach n-values 500 [ 1 + ? ] [
  let unassigned turtles with [ discipline = -1 ]
  ask n-of (min (list group-size (count unassigned))) unassigned [
    set discipline ?
  ]    
]

您可以使用以下命令检查命令中心的结果:

observer> print remove-duplicates map [ count turtles with [ discipline = ? ] ] n-values 500 [ 1 + ? ]
[3]

但我建议更进一步。

让纪律只是数字有点限制。当然,这就是你在传统的数学模型中会做的事情。但这是一个反弹道导弹。您可以随意使用NetLogo。你可以制定你的纪律......乌龟!这将使您的模型更加灵活。你的学科最终可能是异质的:拥有自己的变量,它们可以彼此不同。而且我认为您会发现用代理替换数字会使代码更具可读性。

以下是我想到的完整示例:

breed [ scientists scientist ]
scientists-own [ my-discipline ]
breed [ disciplines discipline ]

to setup
  clear-all
  let nb-scientists 1500
  let nb-disciplines 500
  let group-size 3  
  create-scientists nb-scientists [
    set my-discipline nobody
  ]
  create-disciplines nb-disciplines [
    let unassigned scientists with [ my-discipline = nobody ]
    ask n-of (min (list group-size (count unassigned))) unassigned [ 
      set my-discipline myself
    ] 
  ]
end

您可以检查它是否有效:

observer> setup
observer> print remove-duplicates [ count scientists with [ my-discipline = myself ] ] of disciplines
[3]

但你知道吗?如果是我,我会进一步采取另一个步骤,并使科学家与其学科之间的关系成为实际的NetLogo link。这样,你最终可以设想一个属于(喘息!)不止一门学科的科学家。这是它的样子:

breed [ scientists scientist ]
breed [ disciplines discipline ]

to setup
  clear-all
  let nb-scientists 1500
  let nb-disciplines 500
  let group-size 3
  create-scientists nb-scientists
  create-disciplines nb-disciplines [
    let unassigned scientists with [ not any? my-links ]
    ask n-of (min (list group-size (count unassigned))) unassigned [ 
      create-link-with myself
    ] 
  ]
end

你认为这段代码更好吗?它有效:

observer> print remove-duplicates [ count my-links ] of disciplines
[3]

答案 1 :(得分:1)

尼古拉斯说。但也要考虑这种替代方法:

to test
  let disciplines reduce sentence map [(list ? ? ?)] n-values 500 [? + 1]
  ask turtles [
    set discipline first disciplines
    set disciplines butfirst disciplines
  ]
end

ask是随机排列的,因此我们不需要随机播放disciplines列表。

或者,如果海龟还没有存在,你可以自由地创建它们:

to test
  let disciplines reduce sentence map [(list ? ? ?)] n-values 500 [? + 1]
  foreach shuffle disciplines [
    create-turtles 1 [ set discipline ? ]
  ]
end

在这一个中,我们必须改变学科列表,因为海龟是按照数字顺序创建的。