Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Spiraling integers

by jdporter (Canon)
on Aug 31, 2005 at 15:02 UTC ( #488131=note: print w/replies, xml ) Need Help??


in reply to Spiraling integers

Well, you've already got lots of solutions, but here's mine. I build the spiral, as a 2-d array, from the inside out.
spiral_numbers(5); sub spiral_numbers { my $n = shift; local $_; my @nums = 1 .. $n**2; my @a = ( [ pop @nums ] ); for my $k ( 2 .. $n ) { if ( $k & 1 ) # odd { push @$_, pop @nums for @a[ reverse 0 .. $k-2 ]; unshift @a, my $r=[]; unshift @$r, pop @nums for 1 .. $k; } else # even { unshift @$_, pop @nums for @a[ 0 .. $k-2 ]; push @a, my $r=[]; push @$r, pop @nums for 1 .. $k; } } # print it out local( $\, $, ) = ( "\n", "\t" ); if ( $n & 1 ) # odd { print @$_ for @a; } else # even { print reverse @$_ for reverse @a; } }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://488131]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (6)
As of 2019-10-14 08:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?