Can you help me to find and count sub-sequences of consecutive, identical integer members of a long list (at least 1000 members)? By sub-sequences I mean runs like 0, 0
or 5, 5, 5
.
-
$\begingroup$ Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. $\endgroup$– bbgodfreyOct 2, 2015 at 13:08
-
$\begingroup$ What is "at least"? The answers so far are sufficient for lists of a few thousand or so (unless the operation will be done repeatedly in some tight loop, then even that will add up). For large lists they can be significantly beaten. $\endgroup$– ciaoOct 3, 2015 at 2:39
-
$\begingroup$ @Magnesium ... so, could we help you or is there something left unclear? Maybe you also want to show what you have tried yourself? $\endgroup$– gwrOct 5, 2015 at 10:59
2 Answers
Modifying the approach by @bbgodfrey one might also use Tally
to count all patterns:
list = RandomInteger[{0, 9}, 1000]; (* some integers *)
patternCount = Tally @ Split @ list (* returns a list of {{integer..},count} *)
Now we just take the ones that interest us (e.g. more than one integer):
patternCount2plus = Cases[
patternCount,
{ { Repeated[ _Integer, {2, Infinity} ] }, count_Integer }
]
(* { {{3,3}, 11}, {{4,4}, 8}, ... }*)
This might be sorted by the elements that are repeated and formatted more nicely:
patternCount2plusSorted = SortBy[ patternCount2plus, #[[1,1]]& ];
Grid[
patternCount2plusSorted,
Alignment -> Right,
Background -> { None, { {LightBlue, White} } }, (* alternate rows *)
Frame -> True
]
Giving something like this:
-
1$\begingroup$ Perhaps, your second line of code should be
patternCount = Tally@Split@list
, and your thirdpatternCount2plus = Cases[patternCount, {{Repeated[_Integer, {2, Infinity}]}, count_Integer}]
. $\endgroup$ Oct 2, 2015 at 17:38 -
$\begingroup$ @bbgodfrey Yes, of course, thank you. That happens when one copies like the monks in medieval times. ;-) $\endgroup$– gwrOct 2, 2015 at 18:39
If the List
is named lst
, then
rept = Cases[Split[lst], z_ :> z /; Length[z] > 1]
finds all runs of repeated integers, and
Length[rept]
finds the number of them. Applied to
lst = {1, 2, 3, 3, 4, 5, 5, 5, 6, 4}
they give
(* {{3, 3}, {5, 5, 5}} *)
(* 2 *)
If only the number of repeated runs is desired, then
Count[Split[lst], z_ /; Length[z] > 1]
can be used. For instance,
SeedRandom[5];
Table[Count[Split[RandomInteger[{0, 9}, 10^i]], z_ /; Length[z] > 1], {i, 1, 6}]
(* {2, 9, 93, 890, 9063, 90270} *)