roboticus,
Thank you. I have a real hard time thinking recursively for some reason. There are some things that I would want to change. For instance, letting the call stack be handled automatically by the recursion and not relying on lexicals visible at the package level. Here is my take on satisfying those two changes:
my %net = (...); # shortened for brevity sake
print find_path('1.2.3.4', '1.2.3.6', \%net);
sub find_path {
my ($beg, $end, $net, $seen, $stop, $node, $path) = @_;
if (! defined $stop) {
($node, $path) = ($beg, $beg);
$stop->{$_} = 1 for @{$net->{$end}};
}
return $path if $node eq $end;
return "$path=>$end" if $stop->{$node};
return undef if $seen->{$node}++;
for (@{$net->{$node}}) {
my $found = find_path($beg, $end, $net, $seen, $stop, $_, "$pa
+th=>$_");
return $found if $found;
}
return 'path not found';
}
I liked the iterative solution better because I could alter the search process by adjusting the
shift/
unshift and
push/
pop. I thought recursive solutions were supposed to be more elegant. Perhaps it is just because I don't know what I am doing.
-
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.