01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 01 02 03 04 12 13 15 05 11 16 15 06 10 09 08 07 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 01 02 03 04 05 16 17 18 19 06 15 24 25 20 07 14 23 22 21 08 13 12 11 10 09 ##```## #!/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; } ```