81 chars to recursively construct the 2d array (not including "
sub f {}"):
sub f {
#234567890123456789012345678901234567890123456789012345678901234567890
+12345678901
my$x=my$i=pop;$x?([1..$x],map[(map$_+2*$x-1,reverse@$_),++$i],reverse
+f($x-1)):()
}
The first argument is the dimension of the spiral.
## print "@$_\n" for f(5);
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
The recursive pattern is the following: An n x n spiral looks like this:
+---------------+
| 1 2 3 ... n |
| +-------+ n+1 |
| | | . |
| | *** | . |
| | | . |
| +-------+ 2n-1|
+---------------+
where the *** box is the (n-1) x (n-1) spiral, rotated 180 degrees and 2n-1 added to each component.
Update: oops, moved a reverse to the right spot (didn't affect char count).
-
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.