MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Counting Runs


I do not know if it is elegant or not, but here is what I think:


On Nov 4, 2004, at 1:50 AM, Gregory Lypny wrote:

> Looking for an elegant way to count runs to numbers in a series.
> Suppose I have a list of ones and negative ones such as
> 	v={1,1,1,-1,1,1,1,1,1,-1,-1,-1,-1,1}.
> I'd like to create a function that counts the number of runs of 1s and
> -1s, which in this case is 3 and 2.
>
> 	Greg
>
>
>

In[1]:=
v = {1, 1, 1, -1, 1, 1, 1, 1,
    1, -1, -1, -1, -1, 1}
Out[1]=
{1, 1, 1, -1, 1, 1, 1, 1, 1,
   -1, -1, -1, -1, 1}

In[20]:=
(Length[#1] & ) /@
   Split[Sort[Split[First /@
       Split[v]]]]
Out[20]=
{2, 3}

or without the infix notation:
Map[Length[#] &, Split[Sort[Split[Map[First, Split[v]]]]]]

Note that Sort is sorting Ascending, so the number of runs for the 
smallest value is first.

It works for more than two distinct values, for example:
In[21]:=
rn = Table[Random[Integer,
     {1, 5}], {i, 1, 50}]
Out[21]=
{1, 1, 5, 5, 4, 1, 5, 3, 2,
   5, 3, 5, 5, 5, 2, 5, 5, 4,
   4, 4, 4, 1, 5, 2, 2, 2, 2,
   5, 5, 3, 1, 2, 1, 3, 3, 4,
   4, 3, 1, 3, 5, 1, 4, 4, 4,
   3, 2, 3, 4, 4}

In[22]:=
(Length[#1] & ) /@
   Split[Sort[Split[First /@
       Split[rn]]]]
Out[22]=
{7, 5, 8, 5, 8}

János
-------------------------------------------------------------------
János Löbb
Yale University School of Medicine
Department of Pathology
Phone: 203-737-5204
Fax:      203-785-7303
E-mail: janos.lobb at yale.edu


  • Prev by Date: Re: Garbage collection problem
  • Next by Date: Re: Problems about Graphics
  • Previous by thread: Re: Counting Runs
  • Next by thread: Re: Counting Runs