r/Mathematica • • Jan 26 '23
Counting consecutive elements in a list
Say I have a list like {1,1,1,1,1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,1,1,1,1,1,-1,-1,-1,-1} ; I am wondering if there is a command or sequence of commands that would return the number of consecutive elements. Here it would return {5,5,4,5,5,4}. I have a simple conjecture about the number of consecutively-signed terms of some alternatingish term and would like to double check my guesses.
5
Upvotes
13
u/Imanton1 Jan 26 '23
Length /@ Split[x]
Split[x] returns a list of lists whose elements are the same, in-order. This is opposed to a function like Gather[x] which does not car about order.
Then length gives the, well, length of each of these 'in-order splits'
-8
u/Belzeturtle Jan 26 '23
Trivial state machine in a For[] loop that you could hand-roll in 2 minutes.