2
$\begingroup$

Given a list of character pairs like {{"w", "u"}, {"a", "j"}, {"c", "s"}, {"s", "l"}, ....}, I would like to group the reversed set pairs and then get a total count for each unique character pair. e.g. {"w", "u"} and {"u", "w"} as

    SeedRandom[2222];
    a = Partition[RandomChoice[CharacterRange["a", "z"], 10000], 2]; 
    b = PositionIndex[a];

    a[[b[{"w", "u"}] \[Union] b[{"u", "w"}] ]] 

Gives the set

{{"w", "u"}, {"u", "w"}, {"u", "w"}, {"u", "w"}, {"u", "w"}, {"u", "w"}, {"u", "w"}, {"w", "u"}, {"w", "u"}, {"w", "u"}, {"w", "u"}, {"u", "w"}, {"u", "w"}}

My initial approach was to Sort the keys and find the matching reversed pair using

   sa = Sort[ Keys[b]];
   If [Position[sa, {#[[2]], #[[1]]}][[1, 1]] >= Position[sa, {#[[1]],#[[2]]}][[1, 1]], 
      {Position[sa, {#[[1]], #[[2]]}][[1, 1]], Position[sa, {#[[2]], #[[1]]}][[1, 1]]},
       Null] & /@ sa

to give me the pairs but it fails for cases that do not repeat. Sure I'm missing an easier way.

$\endgroup$
5
  • 2
    $\begingroup$ Are you looking for CountsBy[a, Sort]? There's also GroupBy and the older corresponding functions GatherBy and Tally. $\endgroup$
    – Szabolcs
    Feb 17, 2016 at 15:43
  • $\begingroup$ @Szabolcs I am looking for the indexes or set of pairs like the example across all the of the pair groupings. From that result I can get the count using Length /@ % $\endgroup$
    – ex-kiwi
    Feb 17, 2016 at 16:16
  • 1
    $\begingroup$ These seem related: (44), (1302), (5799), (11906), (17041) $\endgroup$
    – Mr.Wizard
    Feb 17, 2016 at 17:28
  • 1
    $\begingroup$ @ex-kiwi Did you look at the GroupBy function that I also suggested? $\endgroup$
    – Szabolcs
    Feb 17, 2016 at 18:42
  • $\begingroup$ @ Szabolics I see @rhermans beat me to it. The only other thing I would like is to extract the PositionIndex for the pairs which the GatherBy does not supply. Thanks. $\endgroup$
    – ex-kiwi
    Feb 18, 2016 at 17:55

1 Answer 1

4
$\begingroup$

I think @Szabolcs already gave you the answer.

SeedRandom[2222];
a = Partition[RandomChoice[CharacterRange["a", "z"], 10000], 2];
GatherBy[a, Sort]

Mathematica graphics

Length /@ GatherBy[a, Sort] === Normal[CountsBy[a, Sort]][[All, 2]]
True
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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