MathGroup Archive 2008

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

Search the Archive

Re: Pattern problem: How to count from a long list of numbers

  • To: mathgroup at smc.vnet.net
  • Subject: [mg87427] Re: [mg87393] Pattern problem: How to count from a long list of numbers
  • From: Carl Woll <carlw at wolfram.com>
  • Date: Thu, 10 Apr 2008 02:13:42 -0400 (EDT)
  • References: <200804090956.FAA25006@smc.vnet.net>

Nasser Abbasi wrote:

>Hello;
>
>I think using Pattern is my weakest point in Mathematica.
>
>I have this list, say this: (it is all a list of integers, no real numbers).
>
>x = {1, 3, 3, 3, 2, 3, 3, 1, 3, 3}
>
>And I want to count how many say a 3 followed immediately by 3. So in the 
>above list, there will be 4 such occurrences. And if I want to count how 
>many 1 followed by a 3, there will be 2 such cases, etc...
>
>I tried Count[] but I do not know how to set the pattern for "3 followed by 
>a comma followed by 3" or just "3 followed immediately by 3".
>
>I tried few things, such as the following
>
>In[68]:= Count[x, {3, 3}_]
>Out[68]= 0
>
>Also tried Cases, but again, I am not to good with Patterns, so not sure how 
>to set this up at this moment.
>
>Any ideas will be appreciated.
>
>Nasser
>I really need to sit down and study Patterns in Mathematica really well one 
>day :) 
>
>  
>
If you have long lists and would like this to be very quick, I would do 
this by basically finding out the locations of the first and second 
elements, and seeing where the two line up. Here is a function that will 
do this:

pairCount[data_, p1_, p2_] :=  Total @ BitAnd[
    Clip[Clip[Most[data], {p1, p1}, {p1 - 2, p1 - 2}], {p1 - 1, p1 - 1}, 
{0, 1}],
    Clip[Clip[Rest[data], {p2, p2}, {p2 - 2, p2 - 2}], {p2 - 1, p2 - 1}, 
{0, 1}]
]

A couple examples:

In[146]:= pairCount[{1, 3, 3, 3, 2, 3, 3, 1, 3, 3}, 3, 3]

Out[146]= 4

In[147]:= pairCount[{1, 3, 3, 3, 2, 3, 3, 1, 3, 3}, 1, 3]

Out[147]= 2

Carl Woll
Wolfram Research


  • Prev by Date: Re: Just primitive ColorFunction
  • Next by Date: Re: Pattern problem: How to count from a long list of numbers all
  • Previous by thread: Re: Pattern problem: How to count from a long list of numbers all occurrences of 2 numbers next to each others?
  • Next by thread: Re: Re: Pattern problem: How to count from a long list of numbers