Re: Counting Runs

*To*: mathgroup at smc.vnet.net*Subject*: [mg51938] Re: [mg51890] Counting Runs*From*: János <janos.lobb at yale.edu>*Date*: Fri, 5 Nov 2004 02:18:05 -0500 (EST)*References*: <200411040650.BAA18131@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

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

**References**:**Counting Runs***From:*Gregory Lypny <gregory.lypny@videotron.ca>