Somewhat belated, but I had fun exploring different methods. Whether this is better in any way I doubt, but somebody might find it interesting.
#! perl -slw
use strict;
use Data::Dumper;
sub unwindDependancies{
my ($hashref) = @_;
my %copy = %{$hashref};
my @keys = keys %$hashref;
my @deps;
for (@keys) {
next unless exists $copy{$_};
push @deps, [ $_ ];
while( exists $hashref->{$_}) {
unshift( @{ $deps[-1] }, $_ = $hashref->{$_} );
@{$deps[-1]} > @keys and die('Circular reference found inv
+olving:', "@{$deps[-1]}");
delete $copy{$_};
}
}
my %h;
for (@deps) {
my $r = \%h;
$r = exists $r->{$_} ? $r->{$_} : ($r->{$_} = {}) for @$_;
}
#print Dumper \%h;
my (@order, @stack);
my $r=\%h;
my $t=0;
{
while(my ($key, $val) = each %$r) {
push @order, $key;
push(@stack, $r), $r = $val, next if keys %$val;
}
$r = pop(@stack), redo if @stack;
}
# print "@order";
return @order;
}
my %test = ( qw[A B B C D E E F F G G C J H H F I H K H N M
+ O P P Q Q N S U T V]);
print join' ', unwindDependancies \%test;
my %replace = ( qw/
COM SEC
MOB HIS
MOC COM
ICM1 INO
ICM2 INO
EU HIS
CY GRE
AE MOB
IN ICC
GR GRE
MH MOC
CO MOC
MO HIS
/ );
print join' ', unwindDependancies \%replace;
__DATA__
C:\test>238721
V T C G F H I J K E D B A U S M N Q P O
ICC IN SEC COM MOC CO MH HIS EU MO MOB AE GRE CY GR INO ICM1 ICM2
Examine what is said, not who speaks.
1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible
3) Any sufficiently advanced technology is indistinguishable from magic.
Arthur C. Clarke.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.