如何获取列表中连续项目的频率?



如何在Netlogo中获取列表中连续数字的频率?

例如,如果我的列表是:

list = [1 1 1 0 0 1 1 0 1 1 0 0 0 ]

然后输出应如下所示:

output = [3 2 2 1 2 3]

我已经决定这是一个递归的工作:

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启蒙。

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

最新更新