#!/usr/bin/perl -w
use strict;
# The width of our square
# ($ARGV[0] or 5 if no arguments given):
my $n= (@ARGV,5)[0];
# Our square, of size $n+1 x $n+1 due to the sentinel values:
my @s= ( ( (0)x$n, -1 )x$n, (-1)x$n, -1 );
# The directions we will move (right, down, left, up)
# since from $s[$p], $s[$p+1] is just to the right and
# $s[$p-$n-1] is just above:
my @d= ( 1, $n+1, -1, -$n-1 );
# Our starting direction, an index into @d; 0 for "right", $d[0]:
my $d= 0;
# Our starting position (index into @s); -1 so our first step
# to the right will land us at $s[0]:
my $p= -1;
# Our starting value (to be stored into @s);
# 0 so we'll enter 1 after our first step:
my $v= 0;
# Take a step ($p +=). If that step lands on an occupied
# spot, then we're done. So continue while zero (not true):
while( ! $s[ $p += $d[$d] ] ) {
# Store the next value where we just stepped to:
$s[$p]= ++$v;
# Look where we will step next.
# If occupied (not zero, i.e. true)...
if( $s[ $p + $d[$d] ] ) {
# ...then switch to the "next" direction in @d
# wrapping back to $d[0] if needed:
$d= ($d+1) % @d;
}
}
# Print out the 1..$v values plus $n newlines represented
# by the first $v+$n elements of @s:
for( @s[ 0 .. $v+$n-1 ] ) {
# Sentinel values represent newlines:
if( $_ < 0 ) {
print $/;
} else {
# Otherwise left-justify the value, just
# wide enough to hold the largest value, $v:
printf " %".length($v)."d", $_;
}
}