Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[Mathematica] Finding equal elements in a list

  1. Jul 27, 2011 #1
    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. jcsd
  3. Jul 27, 2011 #2
    Length@Cases[{{1, 2, 3}, {1, 2, 4}, {1, 1, 2}}, {a_, a_, ___}]
     
  4. Jul 27, 2011 #3
    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?
     
  5. Jul 28, 2011 #4
    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}};
    So, how about
    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}}
     
     
  6. Jul 28, 2011 #5
    Thanks a ton!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: [Mathematica] Finding equal elements in a list
  1. Lists in mathematica (Replies: 4)

Loading...