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.
CountsBy[a, Sort]
? There's alsoGroupBy
and the older corresponding functionsGatherBy
andTally
. $\endgroup$Length /@ %
$\endgroup$GroupBy
function that I also suggested? $\endgroup$PositionIndex
for the pairs which theGatherBy
does not supply. Thanks. $\endgroup$