选择海龟中最常见的两种颜色并列出它们

时间:2016-05-19 03:17:27

标签: netlogo

我被困在一个简单的程序上。我有一个有两种海龟品种的模型:公民和政府。我想问政府:1)计算并列出foreach颜色,有多少市民有颜色? 2)两种最常见的颜色是什么? 3)将颜色添加到列表中,4)查看邻居在列表中是否具有相同的两个项目。我需要前3分的帮助。

我试过以下的记者

to-report frequency [i lst]
  report length filter [? = i] list
end

我尝试使用此代码

to top-ideas
  ask governments [
    let x citizens with [idcit = [idgov] of myself]  ;; this are the citizens of controlled by the government
    let xlist [5 15 25 35 45 55 65 85 95 125] ;; this is my list of possible colors
    foreach sort xlist [ ask ? [ 
        let y count x with [color = ?]]]]
  end

此代码不完整。您对如何进行有任何建议吗?

感谢您的帮助。

修改:删除了其他问题

1 个答案:

答案 0 :(得分:1)

使用表扩展可以更有效地完成计数,但这可以帮助您入门:

breed [gvts gvt]
breed [cits cit]

gvts-own [most-common] ;get rid of id
cits-own [my-gvt]  ; use the gvt rather than an id

globals [all-colors]  ;avoid repeated list creation

to setup
  ca
  set all-colors [5 15 25 35 45 55 65 85 95 125]
  create-gvts 2
  create-cits 25 [
    set color one-of all-colors
    set my-gvt one-of gvts
  ]
end

to top-ideas
  ask gvts [
    let _mine cits with [my-gvt = myself]  ;no ids
    let _cts color-counts-desc _mine
    set most-common map first sublist _cts 0 2
  ]
end

to-report color-counts-desc [#agts]  ;most of the answer is HERE
  let _cs [color] of #agts
  let _cts map [list ? (freq ? _cs)] all-colors
  report sort-by [last ?1 >= last ?2] _cts
end

;;this is from the documentation for reduce
;; count the number of occurrences of an item in a list
to-report freq [#x #lst]
  report reduce
    [ifelse-value (?2 = #x) [?1 + 1] [?1]] (fput 0 #lst)
end