Netlogo - 给定 2+ 海龟的代理集,找到最常见的颜色

Netlogo - Given an Agentset of 2+ Turtles, find the most frequent color

给定两个或更多海龟的代理集,我如何找到最常见的颜色?

如果可能的话,我想做这样的事情:

set my_color [mostfrequentcolor] of my_agentset

使用此示例设置:

to setup
  ca
  crt 10 [
    set color one-of [ blue green red yellow ]
  ]
  print most-frequent-color turtles 
  reset-ticks
end

您可以使用 to-report 程序来执行此操作-评论中的详细信息:

to-report most-frequent-color [ agentset_ ]
  ; get all colors of the agentset of interest
  let all-colors [color] of agentset_

  ; get only the unique values
  let colors-used remove-duplicates all-colors

  ; use map/filter to get frequencies of each color
  let freqs map [ m -> length filter [ i -> i = m ] all-colors ] colors-used

  ; get the position of the most frequent color (ties broken randomly) 
  let max-freq-pos position ( max freqs ) freqs 

  ; use that position as an index for the colors used
  let max-color item max-freq-pos colors-used

  report max-color
end

这里还有两个选项,都使用了 table 扩展名:

extensions [ table ]

to-report most-frequent-color-1 [ agentset ]
  report (first first
    sort-by [ [p1 p2] -> count last p1 > count last p2 ]
    table:to-list table:group-agents turtles [ color ])
end

to-report most-frequent-color-2 [ agentset ]
  report ([ color ] of one-of first
    sort-by [ [a b] -> count a > count b ]
    table:values table:group-agents turtles [ color ])
end

我不太确定我更喜欢哪一个...

您正在寻找 modes 原语 (https://ccl.northwestern.edu/netlogo/docs/dictionary.html#modes):

one-of modes [color] of my_agentset

它是 "modes",复数形式,因为可能会出现平局。打破平局的一种方法是使用 one-of 进行随机选择。