2

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.

ex-kiwi
  • 157
  • 5

1 Answers1

4

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
rhermans
  • 36,518
  • 4
  • 57
  • 149