Skip to main content

pattern matching - Find the length of repeating numbers in a list


a = 4;
primes = Prime[Range[PrimePi[10^(a - 1)] + 1, PrimePi[10^a]]];

d = 1;
Cases[IntegerDigits[primes], {_, d .., _}]

This gets me the list of the numbers from my list of primes that have more than one 1 in a row.


{{1, 1, 1, 7}, {2, 1, 1, 1}, {2, 1, 1, 3}, {3, 1, 1, 9}, {4, 1, 1, 1},
{5, 1, 1, 3}, {5, 1, 1, 9}, {6, 1, 1, 3}, {8, 1, 1, 1}, {8, 1, 1, 7}}

Is there a way to get the length of the repeating digits? For instance, I'd rather get an output of


{3,3,2,2,3,2,2,2,3,2}


My goal is to get the count of the ones with the maximum length.



Answer



I emphasize that the OP wanted the longest sequence of 1s in a row.


Consider


it = {{1, 1, 1, 2, 2, 2, 2, 1, 1}}

Then, xavier's comment gives


Cases[it, id : {_, 1 .., _} :> Count[id, 1]]



{}



and Wouter's answer:


Max[Last /@ Tally[#]] & /@ it


{5}



which is incorrect.





This works:


Max /@ (Length /@ Select[#, MemberQ[#, 1] &] & /@ Split /@ it)


{3}



and on the exemplary


it = {{1, 1, 1, 7}, {2, 1, 1, 1}, {2, 1, 1, 3}, {3, 1, 1, 9}, {4, 1, 1, 1},
{5, 1, 1, 3}, {5, 1, 1, 9}, {6, 1, 1, 3}, {8, 1, 1, 1}, {8, 1, 1, 7}}


gives



{3, 3, 2, 2, 3, 2, 2, 2, 3, 2}





If 1 is dominant in all sublists (i.e., for sure the longest subsequence of repeating numbers consists of 1s), like in the case of the last it, this will also work:


Length /@ Last /@ Sort /@ Split /@ it

Comments