# Count two or more equal consecutive elements in a list and create histogram

I have a list generated by:

list = RandomInteger[{1}, 100]


it contains only 0's and 1's

{0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, \
0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, \
1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, \
0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, \
0, 1, 0, 0, 0, 0, 1, 1}


I'm trying to create a histogram in the following way: I want to look for two or more consecutive 1's e.g. 1,1 or 1,1,1 and so on. In other words I want to count all sequences of two or more consecutive 1's.

I also want to extract the positions of the found sequences in the list.

I tried to approach it with PatternSequence based on the help entry e.g.:

list //. {x___, PatternSequence[1, 1], y___} -> {x, "mypatterns", y}


which seems ok for showing me where the patterns in the list are, but it does not count them or give me the positions :(

Looking for some inspiration :)

• Split is you friend here :-) – Szabolcs Jul 9 '15 at 11:42
• Histogram: Histogram[Length /@ Select[Split[list], First[#] == 1 &]]. Positions: pos = Accumulate[Length /@ Split[list]]. Positions of the ones having 1s: Pick[pos, First/@Split[list], 1]. – Szabolcs Jul 9 '15 at 12:04
• Thanks. Using Select and Split is actually very nice :), the histogram works for me here although it includes the patterns with only one 1. I don't understand the Positions code since I want e.g. the positions of the pattern with two 1's, three 1's in the original list, i.e. when does the pattern start and when does it end. – holistic Jul 9 '15 at 12:24
• See this similar post for the counting problem. – SquareOne Jul 9 '15 at 12:50

Rewritting, after author made clearer what was expected

   list = RandomInteger[{1}, 1000];
PositionsOfNumeroUno = Flatten[Position[list, 1]];
PositionOfSequencesOFNumeroUno =Table[{n, {ListOfPositions =Pick[Drop[PositionsOfNumeroUno, n - 1],Differences[PositionsOfNumeroUno, 1, n - 1], n - 1] - n + 1,ListOfPositions + n - 1} // Transpose}, {n, 2, 10, 1}]


This will give a list which will have as a first value how long is the sequences, and then the list of positions where this sequences occurs. Here I done it for up to lenght of 10 entries. To get how many entries there are of each length

HowLongAreSequences = {PositionOfSequencesOFNumeroUno[[All, 1]],   Map[Length[#] &, PositionOfSequencesOFNumeroUno[[All, 2]]]} //Transpose


Below I also plot results of the last command for a bit larger sample (10000 entries long). With blue I shown calculated value, and with orange the expected value (just from probability arguments, how many occuranges of such sequence I would expect in the sample)

• Great, thank you :) – holistic Jul 10 '15 at 12:15