Tanktalus has asked for the wisdom of the Perl Monks concerning the following question:
I have many (sometimes more than 100) tasks to perform in perl. Some of these tasks are concerned with order (task a must complete before task c, for example). Others may not care about order (independant of other tasks). There are no loops (e.g., a may require c, but c may not require a, even indirectly). Note that there is more than one possible solution to this. I'm not concerned with "best" (I can't even define "best"). I'm merely concerned with coming up with a valid solution, one that, given the same input (same list of tasks, same requirements) gives the same list (the reason for this is a bit complex, so I won't get into that just now).
I'm trying to come up with a way to get sort to do this. Really, I'm not concerned with having to use sort, but I was thinking sort would be the easy way to do this. It doesn't seem to be. Here is a completely rewritten example of what I'm doing (the original code is thousands of lines long and proprietary).
The output is:use strict; use Data::Dumper; my %before = ( a => _s(qw(c)), b => _s(qw(d e)), c => _s(qw(l)), d => _s(qw(e a)), e => _s(qw(c)), f => _s(qw(g d)), g => _s(qw(c)), h => _s(qw(g i)), i => _s(qw()), j => _s(qw(c)), k => _s(qw()), l => _s(qw()), n => _s(qw(c)), o => _s(qw()), ); print Dumper(\%before); my @order = sort { #print "Checking $a vs $b\n"; prereq($a, $b) <=> prereq($b, $a) } keys %before; print "@order\n"; sub prereq { my ($l, $r) = @_; if (exists $before{$l}{$r}) { return 1; } if (grep { prereq($_, $r) } keys %{$before{$l}}) { return 1; } 0; } # setup - create a hash for easy access sub _s { my %h = map { $_ => 1 } @_; \%h }
I'm expecting that "h" should come after "i" (since h requires i). However, if I uncomment the print in the sort, I notice that h and i aren't even compared.l c e n a d j k g h b f o i
I originally noticed this problem on AIX using perl 5.8.0, and the above code was tested using Linux perl 5.8.5. For many reasons, perl 5.8 is a requirement (XML::Twig works better with 5.8 than 5.6).
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Problems with sorting
by kvale (Monsignor) on Feb 22, 2005 at 00:03 UTC | |
by Tanktalus (Canon) on Feb 22, 2005 at 00:45 UTC | |
Re: Problems with sorting
by Limbic~Region (Chancellor) on Feb 22, 2005 at 01:06 UTC | |
by eyepopslikeamosquito (Archbishop) on Feb 22, 2005 at 05:15 UTC | |
by Tanktalus (Canon) on Feb 22, 2005 at 15:57 UTC | |
Re: Problems with sorting
by TedPride (Priest) on Feb 23, 2005 at 01:47 UTC |