| 1 | # as seen on perl monks: http://www.perlmonks.org/?node_id=488867 |
|---|
| 2 | use v6-alpha; |
|---|
| 3 | |
|---|
| 4 | # The width of our square |
|---|
| 5 | # ($ARGV[0] or 5 if no arguments given): |
|---|
| 6 | my $n = @*ARGS[0] // 5; #/ |
|---|
| 7 | |
|---|
| 8 | # Our square, of size $n+1 x $n+1 due to the sentinel values: |
|---|
| 9 | my @single_line = ( 0 xx $n, -1 ); |
|---|
| 10 | my @last_line = ( -1 xx $n, -1 ); |
|---|
| 11 | my @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: |
|---|
| 16 | my @d = ( 1, $n+1, -1, -$n-1 ); |
|---|
| 17 | |
|---|
| 18 | # Our starting direction, an index into @d; 0 for "right", $d[0]: |
|---|
| 19 | my $d = 0; |
|---|
| 20 | |
|---|
| 21 | # Our starting position (index into @s); 0 so we start at $s[0]: |
|---|
| 22 | my $p = 0; |
|---|
| 23 | |
|---|
| 24 | # Our starting value (to be stored into @s); |
|---|
| 25 | # 0 so we'll enter 1 after our first step: |
|---|
| 26 | my $v = 0; |
|---|
| 27 | |
|---|
| 28 | # So continue while zero (not true): |
|---|
| 29 | |
|---|
| 30 | for 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 | |
|---|
| 45 | my $format = " %" ~ $v.chars ~ "d"; |
|---|
| 46 | for @s { $_ .= fmt($format) }; |
|---|
| 47 | |
|---|
| 48 | for 0 .. $n - 1 -> $y { |
|---|
| 49 | my $start = ($y * ($n+1)); |
|---|
| 50 | my $end = $start + $n - 1; |
|---|
| 51 | @s[ $start .. $end].say; |
|---|
| 52 | } |
|---|