如何获取Netlogo列表中连续数字的频率?
例如,如果我的列表是:
list = [1 1 1 0 0 1 1 0 1 1 0 0 0 ]
然后输出应如下所示:
output = [3 2 2 1 2 3]
答案 0 :(得分:3)
这不是代码编写服务,但是我得到了nerd sniped,所以就到这里了。我认为这是递归工作:
to-report count-consecutive-items [ xs ]
report count-consecutive-items-loop [] nobody xs
end
to-report count-consecutive-items-loop [ counts-so-far last-item remaining-items ]
report ifelse-value (empty? remaining-items) [
; no more items to count, return the counts as they are
counts-so-far
] [
(count-consecutive-items-loop
(ifelse-value (first remaining-items = last-item) [
; this is the same item as the last,
ifelse-value (empty? counts-so-far) [
; if our list of counts is empty, start a new one
[1]
] [
; add one to the current count and keep going
replace-item (length counts-so-far - 1) counts-so-far (1 + last counts-so-far)
]
] [
; this is an item we haven't seen before: start a new count
lput 1 counts-so-far
])
(first remaining-items)
(but-first remaining-items)
)
]
end
to test
let result count-consecutive-items [1 1 1 0 0 1 1 0 1 1 0 0 0]
print result
print result = [3 2 2 1 2 3]
end
我敢肯定,其他人可以提出一个更好的命令式版本,比这要容易理解的多,但是您可以将其视为教学法:如果您能够理解此代码,它将对您有所帮助在您获得NetLogo启发的过程中。
(我现在没有时间写说明,但是如果您需要特别帮助,请在评论中提问。)
答案 1 :(得分:2)
to-report countRuns [#lst]
if 0 = length #lst [report #lst]
let val first #lst
let _ct 1
let cts []
foreach butfirst #lst [? ->
ifelse ? = val [
set _ct (1 + _ct)
][
set cts lput _ct cts
set val ?
set _ct 1
]
]
report lput _ct cts
end