Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Ah, a topological sort. Which you can be reduced to sorting if there are no conflicting requirements. (Sometimes you can do a topological sort faster than an ordinary sort, but you never need more time than a regular sort).

I'd preprocess the 'pred' arrays so I can faster search in them, after that, I'd do a regular sort:

#!/usr/bin/perl use strict; use warnings; my %hash = ( MEX1J => { desc => 'Job 2', pred => [qw /TEX1J/], }, MEX2J => { desc => 'Job End', pred => [qw /TEX1J MEX1J/], }, TEX1J => { desc => 'Job start', pred => [], }, ); # # Preprocess, transform the 'pred' arrays into hashes. # while (my ($key, $value) = each %hash) { $value->{pred_h} = {map {($_, 1)} @{$value->{pred}}}; } # # Sort keys. # my @keys = sort {$hash{$b}{pred_h}{$a} ? -1 : $hash{$a}{pred_h}{$b} ? 1 : 0} keys %hash; # # Print keys. # print "$_\n" for @keys; __END__ TEX1J MEX1J MEX2J
Note that you can write the sort block as:
{$hash{$a}{pred_h}{$b} - $hash{$b}{pred_h}{$a}}
but that's rather obscure, and you'd need to turn off warnings.
Perl --((8:>*

In reply to Re: Sort Algorithm (recursive?) by Perl Mouse
in thread Sort Algorithm (recursive?) by bertigo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-03-29 14:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found