Netlogo - 如何获取列表中连续项目的频率?
Netlogo - How to get freq of consecutive items in list?
如何在 Netlogo 中获取列表中连续数字的频率?
例如,如果我的列表是:
list = [1 1 1 0 0 1 1 0 1 1 0 0 0 ]
那么输出应该如下所示:
output = [3 2 2 1 2 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。
(我现在没有时间写解释,但如果有什么特别需要帮助的,请在评论中提问。)
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
如何在 Netlogo 中获取列表中连续数字的频率?
例如,如果我的列表是:
list = [1 1 1 0 0 1 1 0 1 1 0 0 0 ]
那么输出应该如下所示:
output = [3 2 2 1 2 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。
(我现在没有时间写解释,但如果有什么特别需要帮助的,请在评论中提问。)
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