Magic squares/Raku: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (→{{header|Perl 6}}: Clean up and refactor a bit. Randomize the magic square generation.) |
Thundergnat (talk | contribs) m (→{{header|Perl 6}}: Meh. tried to be cute and ended up wrong.) |
||
Line 1: | Line 1: | ||
Rather than having multiple examples for different orders of magic square, this will generate a magic square for ''any'' valid n x n grid |
Rather than having multiple examples for different orders of magic square, this will generate a magic square for ''any'' valid n x n grid. |
||
Invoke at the command line and pass in the desired size as a parameter. |
Invoke at the command line and pass in the desired size as a parameter. |
||
Line 14: | Line 15: | ||
my @sq; |
my @sq; |
||
my $i = 1; |
my $i = 1; |
||
⚫ | |||
⚫ | |||
gen-sq($n); |
gen-sq($n); |
||
⚫ | |||
my @r = ^$n .pick(*); |
|||
⚫ | |||
say "\nThe magic number is ", [+] @sq[0].list; |
say "\nThe magic number is ", [+] @sq[0].list; |
||
Line 37: | Line 39: | ||
my $y = 0; |
my $y = 0; |
||
@sq[$i % $n ?? $y !! $y++][($i-1) % $n] = $i++ for ^$n²; |
@sq[$i % $n ?? $y !! $y++][($i-1) % $n] = $i++ for ^$n²; |
||
⚫ | |||
for ^$q -> $r { |
for ^$q -> $r { |
||
for $q ..^ $n - $q -> $c { |
for $q ..^ $n - $q -> $c { |
||
Line 49: | Line 50: | ||
multi sub gen-sq ($n where {$n %% 2 and $n % 4}) { # singly even |
multi sub gen-sq ($n where {$n %% 2 and $n % 4}) { # singly even |
||
⚫ | |||
my $q = $n div 4; |
|||
gen-sq($h); |
gen-sq($h); |
||
$i *= 4; |
$i *= 4; |
||
Line 63: | Line 62: | ||
(@sq[$r;$c], @sq[$r + $h;$c]) = (@sq[$r + $h;$c], @sq[$r;$c]); |
(@sq[$r;$c], @sq[$r + $h;$c]) = (@sq[$r + $h;$c], @sq[$r;$c]); |
||
} |
} |
||
if $h > 4 { |
|||
⚫ | |||
if $h > 4 { |
|||
for ^$h -> $r { |
|||
for ($n - $q + 1) ..^ $n -> $c { |
for ($n - $q + 1) ..^ $n -> $c { |
||
(@sq[$r;$c], @sq[$r + $h;$c]) = (@sq[$r + $h;$c], @sq[$r;$c]); |
(@sq[$r;$c], @sq[$r + $h;$c]) = (@sq[$r + $h;$c], @sq[$r;$c]); |
||
} |
} |
||
} |
} |
||
} |
} |
||
⚫ | |||
} |
} |
||
}</lang> |
}</lang> |