root/examples/spiral_numbers.pl

Revision 13549, 1.4 kB (checked in by markstos, 2 years ago)

spiral_numbers.pl -> s/as(/fmt(/

  • Property svn:mime-type set to text/plain; charset=UTF-8
  • Property svn:eol-style set to native
Line 
1# as seen on perl monks: http://www.perlmonks.org/?node_id=488867
2use v6-alpha;
3
4# The width of our square
5# ($ARGV[0] or 5 if no arguments given):
6my $n = @*ARGS[0] // 5;      #/
7
8# Our square, of size $n+1 x $n+1 due to the sentinel values:
9my @single_line = ( 0  xx $n, -1 );
10my @last_line   = ( -1 xx $n, -1 );
11my @s = ( @single_line xx $n, @last_line);
12
13# The directions we will move (right, down, left, up)
14# since from $s[$p], $s[$p+1] is just to the right and
15# $s[$p-$n-1] is just above:
16my @d = ( 1, $n+1, -1, -$n-1 );
17
18# Our starting direction, an index into @d; 0 for "right", $d[0]:
19my $d = 0;
20
21# Our starting position (index into @s); 0 so we start at $s[0]:
22my $p = 0;
23
24# Our starting value (to be stored into @s);
25# 0 so we'll enter 1 after our first step:
26my $v = 0;
27
28# So continue while zero (not true):
29
30for 0 .. $n*$n {
31    # Store the next value where we just stepped to:
32    @s[$p] = ++$v;
33    # Look where we will step next.
34    # If occupied (not zero, i.e. true)...
35    if  @s[ $p + @d[$d] ] {
36        # ...then switch to the "next" direction in @d
37        # wrapping back to $d[0] if needed:
38        $d = ($d+1) % @d;
39    }
40
41    #take the next step
42    $p += @d[$d];
43};
44
45my $format = " %" ~ $v.chars ~ "d";
46for @s { $_ .= fmt($format) };
47
48for 0 .. $n - 1 -> $y {
49    my $start = ($y * ($n+1));
50    my $end   = $start + $n - 1;
51    @s[ $start ..  $end].say;
52}
Note: See TracBrowser for help on using the browser.