[Mathematica] Finding equal elements in a list

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 7K views
SoggyBottoms
Messages
53
Reaction score
0
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?
 
Physics news on Phys.org
Length@Cases[{{1, 2, 3}, {1, 2, 4}, {1, 1, 2}}, {a_, a_, ___}]
 
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?
 
As always, there are multiple ways. Each have advantages and disadvantages with respect to the others (run time, memory usage, readability etc..)

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

So, how about
Code:
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:
ReplaceList[test, {___, A:{a_, a_, _}, {b_, c_, _}, ___}/;b>c :> A]

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

Or
Code:
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}}