I'm surprised that the adjacency list is hardcoded in many of these answers. That's the sort of thing the program should work out, so that you can scale the grid to arbitrary sizes.
I would have chosen to reference tiles by a co-ordinate pair rather than a plain numbers, so for a grid of size $p by $q, the neighbours of each tile ($x,$y) can be calculated like this:
for (my $y = 1; $y <= $q; $y++) {
for (my $x = 1; $x <= $p; $x++) {
for (my $ny=$y-1; $ny<=$y+1; $ny++) {
next if ($ny < 1 || $ny > $q);
for (my $nx=$x-1; $nx<=$x+1; $nx++) {
next if ($nx < 1 || $nx > $p || ($nx == $x && $ny == $y));
push @{$adjlist{"$x,$y"}}, [$nx,$ny];
}
}
}
}
But it's easy enough to calculate tile numbers from the co-ordinates in this loop if required. Note the optimisation where we don't bother to go into the deepest loop if we're off the top or bottom edge.
You could also do it the opposite way, looping through tile numbers from 1 to ($p*$q) and then effectively calculating the x and y position of the current tile in order to work out whether you are near an edge, but this strikes me as likely to be slower as it involves more arithmetic.
-
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.
|