Here goes, interesting little problem ... my solution is non-recursive, can handle loops and allows to write my @order = demangle(\%replace);.
Update
After sleeping over it I've greatly simplified the algoritm, now I think it's elegant. You have to decide yourself if this algorithm is nicer than the rather elegant recursive solution.
sub demangle {
my $r = shift;
my %illegal;
@illegal{%$r} = ();
my @chains;
LOOP:
while (my($k,$v) = each %$r) {
for my $c (@chains) {
if ($c->[-1] eq $k) { # append to end of chain
push @$c, $v;
next LOOP;
};
if ($c->[0] eq $v) { # prepend to start of chain
unshift @$c, $k;
next LOOP;
}
}
push @chains, [$k, $v]; # create new chain
}
# fix circular replacements
for my $c (@chains) {
if ($c->[0] eq $c->[-1]) { # we have a circle
my $new_key;
do {
$new_key = join '', map { ('a'..'z')[rand 26] } 1..8;
} while exists $illegal{$new_key};
$illegal{$new_key}++;
unshift @$c, $new_key;
push @$c, $new_key;
}
}
my @order;
while (@chains) {
push @order, { map { $_->[-2] => pop @$_ } @chains };
@chains = grep @$_ > 1, @chains;
}
return @order;
}
-- Hofmator
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
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.
|
|