#!/usr/bin/perl use strict; use warnings; my $n = $ARGV[0] || 5; my @spiral = gen_spiral($n); output(@spiral); sub output { my @spiral = @_; my $n = sqrt @spiral; my $cnt; for ( @spiral ) { print "\n" if $cnt++ % $n == 0; printf("%-3d ", $_); } } sub gen_spiral { my $n = shift; my ($tot, @spiral) = ($n * $n, ()); my ($index, $cnt, $l_border, $r_border, $fill_size) = (1, 1, 1, $tot, $n + 1); while ( $cnt <= $tot ) { ##### Moving right ##### # Step 1, decrease fill size --$fill_size; # Step 2, fill in for ( 1 .. $fill_size ) { $spiral[ $index++ ] = $cnt++; } --$index; # Step 3, skip by n's for ( 1 .. $fill_size - 1 ) { $index += $n; $spiral[$index] = $cnt++; } ##### Moving left ##### # Step 1, decrease fill size --$fill_size; # Step 2, fill in for ( 1 .. $fill_size ) { $spiral[ --$index ] = $cnt++; } # Step 4, skip by n's for ( 1 .. $fill_size - 1 ) { $index -= $n; $spiral[$index] = $cnt++; } ++$index; } shift @spiral; # Arrays are 0 based return @spiral; }