Mathematica [Mathematica] Finding equal elements in a list

AI Thread Summary
The discussion focuses on finding sublists in Mathematica where specific conditions are met. Initially, the user seeks to identify sublists where the first two elements are equal, which is achieved using the Cases function. They then present a more complex requirement: finding sublists where the first two elements are equal and followed by a sublist with the first element greater than the second. Several methods are suggested, including using Partition and ReplaceList, each with its own advantages regarding runtime and readability. Ultimately, the solution successfully identifies the qualifying sublist {1, 1, 2}.
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}}
 
Thanks a ton!
 

Similar threads

Replies
2
Views
2K
Replies
13
Views
2K
Replies
22
Views
3K
Replies
5
Views
3K
Replies
3
Views
3K
Back
Top