Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
    0: # This is essentially a copy of an old writeup of mine on Everything2.
    1: #
    2: # Here's an implementation of a [topological sort] in Perl.
    3: # It's reasonably terse, and even has some comments!
    4: #
    5: # Pass it as input a list of array [reference]s; these
    6: # specify that that index into the list must come before all
    7: # elements of its array. Output is a topologically sorted
    8: # list of indices, or undef if input contains a cycle. Note
    9: # that you <em>must</em> pass an array ref for every input
    10: # elements (if necessary, by adding an empty list
    11: # reference)!
    12: #
    13: # For instance, tsort ([1,2,3], [3], [3], []) returns
    14: # (0,2,1,3).
    15: 
    16: sub tsort {
    17:   my @out = @_;
    18:   my @ret;
    19: 
    20:   # Compute initial in degrees
    21:   my @ind;
    22:   for my $l (@out) {
    23:     ++$ind[$_] for (@$l)
    24:   }
    25: 
    26:   # Work queue
    27:   my @q;
    28:   @q = grep { ! $ind[$_] } 0..$#out;
    29: 
    30:   # Loop
    31:   while (@q) {
    32:     my $el = pop @q;
    33:     $ret[@ret] = $el;
    34:     for (@{$out[$el]}) {
    35:       push @q, $_ if (! --$ind[$_]);
    36:     }
    37:   }
    38: 
    39:   @ret == @out ? @ret : undef;
    40: }
    41: 
    

In reply to Topological Sort in Perl by ariels

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 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? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2021-12-07 08:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (33 votes). Check out past polls.

    Notices?