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:
-
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.
|