# [Mathematica] Finding equal elements in a list

1. Jul 27, 2011

### SoggyBottoms

I have a nested list of the type:

{{1, 2, 3}, {1, 2, 4}, {1, 1, 2}}

I want to find the number of sublists in which the first two elements are equal, so in this case that's one (the sublist {1, 1, 2}).

Is this possible in Mathematica?

2. Jul 27, 2011

### Simon_Tyler

Length@Cases[{{1, 2, 3}, {1, 2, 4}, {1, 1, 2}}, {a_, a_, ___}]

3. Jul 27, 2011

### SoggyBottoms

Thanks!

I want to do something a little more complicated now that I can't figure out either. I have a nested list again:

{{1, 2, 3}, {1, 2, 4}, {1, 1, 2}, {2, 1, 3}, {1, 1, 3}, {1, 2, 3}}

Now I want to find the number of sublists in which the first two elements are equal AND are followed by a sublist in which the first element is higher than the second.

So in this case I will get the same answer again, one (only the sublist {1, 1, 2} qualifies).

Is this possible as well?

4. Jul 28, 2011

### Simon_Tyler

As always, there are multiple ways. Each have advantages and disadvantages with respect to the others (run time, memory usage, readability etc..)

Code (Text):
test = {{1, 2, 3}, {1, 2, 4}, {1, 1, 2}, {2, 1, 3}, {1, 1, 3}, {1, 2, 3}};
Code (Text):

Partition[test, 2, 1]
First /@ Cases[%, {{a_, a_, _}, {b_, c_, _}} /; b > c]

Out[2]= {{{1, 2, 3}, {1, 2, 4}}, {{1, 2, 4}, {1, 1, 2}}, {{1, 1, 2}, {2, 1, 3}}, {{2, 1, 3}, {1, 1, 3}}, {{1, 1, 3}, {1, 2, 3}}}
Out[3]= {{1, 1, 2}}

Or
Code (Text):

ReplaceList[test, {___, A:{a_, a_, _}, {b_, c_, _}, ___}/;b>c :> A]

Out[4]= {{1, 1, 2}}

Or
Code (Text):

out = {};
Do[If[test[[i, 1]] == test[[i, 2]] && test[[i + 1, 1]] > test[[i + 1, 2]],
PrependTo[out, i]], {i, 1, Length[test]}]
test[[out]]

Out[7]= {{1, 1, 2}}

5. Jul 28, 2011

### Shukie

Thanks a ton!