My goal is to compare two AoAs for equality, where the order of the
elements of the main array and sub arrays is unimportant. Sort of an
equivalence class over permutations. For example, these AoAs are equal:
$ha = [[1,2],
[5,5,5],
[1,2],
[3,4]];
$hb = [[4,3],
[1,2],
[2,1],
[5,5,5]];
Order is unimportant, so the data are set-like, but because there
are repeated elements, we need a hierarchical multiset/bag comparison.
Pulling out Set::Bag, I create
use Set::Bag;
my $bag_a = Set::Bag->new();
my $bag_b = Set::Bag->new();
and then get stuck, because elements must be strings, not anon
arrays. So I create a hack: sort and serialize the arrays at each level:
my @ser_a;
for my $aref (@$ha) {
push @ser_a, join ',', sort {$a <=> $b} @$aref;
}
my @ser_b;
for my $bref (@$hb) {
push @ser_b, join ',', sort {$a <=> $b} @$bref;
}
print "They are ";
unless ( (join ',', sort @ser_a) eq (join ',', sort @ser_b)) {
print "not ";
}
print "equal\n";
This works, but costs sorts, stringifications, and joins. It is
slow. Is there a faster and/or more elegant way to do this?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.