How can i get the freq of consecutive numbers in a list in Netlogo?
For example, if my list is:
list = [1 1 1 0 0 1 1 0 1 1 0 0 0 ]
Then the output should look as follows:
output = [3 2 2 1 2 3]
I have decided that this is a job for recursion:
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
I'm sure that someone else can come up with a nice imperative version that will be much easier to understand than this, but you can consider this as a pedagogical exercise: if you manage to understand this code, it will help you on your way to NetLogo enlightenment.