Re: Pattern problem: How to count from a long list of numbers all occurrences of 2 numbers next to each others?
- To: mathgroup at smc.vnet.net
- Subject: [mg87403] Re: Pattern problem: How to count from a long list of numbers all occurrences of 2 numbers next to each others?
- From: "Nasser Abbasi" <nma at 12000.org>
- Date: Thu, 10 Apr 2008 02:09:12 -0400 (EDT)
- Reply-to: "Nasser Abbasi" <nma at 12000.org>
"Nasser Abbasi" <nma at 12000.org> wrote in message news:...
> 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 :)
Hello;
After more studying this problem, I came up with this solution below. I use
Partitions, then I use Count[]:
x = {1, 3, 3, 3, 2, 3, 3, 1, 3, 3};
allPairs = Partition[x, 2, 1]
Out[38]= {{1, 3}, {3, 3}, {3, 3}, {3, 2}, {2, 3}, {3, 3}, {3, 1},
{1, 3}, {3, 3}}
Count[allPairs, {3, 3}]
Out[39]= 4
Count[allPairs, {1, 3}]
Out[40]= 2
I see what my problem was. Pattern applies to "one element" in the list. So
in the list {a,b,c} It is not possible to make a pattern to find {a,b}?
Since {b,c} are not one element in the list, it is 2 elements.
So what I partitioned the list, now all adjacent pairs of numbers became
individual elements in a new list (a list in a list) so a pattern would work
on {b,c} now since {b,c} is now "one element" in a list.
Nasser