# Matching and counting reversed pairs in a list

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.

• Are you looking for CountsBy[a, Sort]? There's also GroupBy and the older corresponding functions GatherBy and Tally. Feb 17, 2016 at 15:43
• @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 /@ % Feb 17, 2016 at 16:16
• These seem related: (44), (1302), (5799), (11906), (17041) Feb 17, 2016 at 17:28
• @ex-kiwi Did you look at the GroupBy function that I also suggested? Feb 17, 2016 at 18:42
• @ 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. Feb 18, 2016 at 17:55

SeedRandom[2222];

Length /@ GatherBy[a, Sort] === Normal[CountsBy[a, Sort]][[All, 2]]

True