Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Problems with sorting

by kvale (Monsignor)
on Feb 22, 2005 at 00:03 UTC ( [id://433199]=note: print w/replies, xml ) Need Help??


in reply to Problems with sorting

What you want here is called a topological sort. First create a directed dependency graph of tasks and then apply a topological sort to that graph to produce an ordered list of tasks. Happily, there is a module Sort::Topological that accomplishes this task:
my %children = ( 'a' => [ 'b', 'c' ], 'c' => [ 'x' ], 'b' => [ 'x' ], 'x' => [ 'y' ], 'y' => [ 'z' ], 'z' => [ ], ); sub children { @{$children{$_[0]} || []}; } my @unsorted = ( 'z', 'a', 'x', 'c', 'b', 'y' ); my @sorted = toposort(\&children, \@unsorted);
%children gives the dependency graph, and the sub children takes care of the null case.

-Mark

Replies are listed 'Best First'.
Re^2: Problems with sorting
by Tanktalus (Canon) on Feb 22, 2005 at 00:45 UTC

    Thank you - that looks extremely promising. I really, really like that it uses a call-back to get the dependancies rather than asking for a complete list of dependancies up front. Since S::T has to loop through everything anyway, why loop through it in the calling code, too, when a callback will implicitly perform the loop?

    It does seem to perform the sort in the reverse order of what I wanted, but thankfully perl makes that pretty darned trivial.

    For posterity, my example has changed to:

    use Sort::Topological; 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 = reverse Sort::Topological::toposort( sub { @{$before{$_[0]}}; }, [ keys %before ], ); print "@order\n"; sub _s { [ @_ ]; #my %h = map { $_ => 1 } @_; #\%h }
    And the result is:
    l c a e i g d o f b h k j n
    At this point, this (simple) example is working. Which gives me reasonable confidence since I did manage to create a non-working example in the first place. Again, thanks!

    The only issue is that the module drags in too much - too bad it wasn't separated out into its own distribution. Oh well, can't win 'em all!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://433199]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2024-04-26 07:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found