6
$\begingroup$

I have a List, for example (assume it's always ordered like this one):

myList = {6, 6, 8, 10, 14}

I would like to get a result like this:

desiredResult = {{6,2}}

in other words "6 appears more than once. Nothing else appears more than once"

This is where I'm at now - clearly only partway there.

partialResult = 
 Table[Cases[myList, myList[[i]] ..], {i, 1, Length[myList]}] // DeleteDuplicates

which gives me this result:

partialResult = {{6, 6}, {8}, {10}, {14}}

and then

finalResult = 
  Table[
   {partialResult[[i, 1]], Length[partialResult[[i]]]}, 
   {i, 1,  Length[partialResult]}]

gives me almost desiredResult, but I'm not satisfied. My solution seems clunky. I'd love to see an elegant solution to this - there has to be a cleaner, more pleasing way to do this. It's using functions, but the repeated use of Table & Length, and the egregious DeleteDuplicates just feels like disguised procedural code.

I'd really appreciate seeing better ways to get partialResult and finalResult (I could learn a lot from those two items), but I expect that there's a better way to do it than the multi-step.

$\endgroup$
2
  • 3
    $\begingroup$ Look up Tally and combine with Cases. $\endgroup$
    – kale
    Commented Sep 12, 2015 at 3:21
  • 2
    $\begingroup$ The extend @kale's comment Select[Tally[myList], #[[2]] > 1 &] $\endgroup$ Commented Sep 12, 2015 at 3:26

1 Answer 1

9
$\begingroup$
myList = {6, 6, 8, 10, 14};
partialR = Gather@myList
(*{{6, 6}, {8}, {10}, {14}}*)

Cases[partialR, x_ /; Length@x > 1 :> {First@x, Length@x}]
(*{{6, 2}}*)

However, the following gives you the final result in a straightforward way:

Select[Tally[myList], #[[2]] > 1 &] 
(*{{6, 2}}*)
$\endgroup$
1
  • 2
    $\begingroup$ Or the corresponding Association way: Select[Counts[myList], # > 1 &]. $\endgroup$
    – march
    Commented Sep 12, 2015 at 6:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.