Magic squares/Raku: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) (→{{header|Perl 6}}: Add a few comments) |
Thundergnat (talk | contribs) m (→{{header|Perl 6}}: Clean up and refactor a bit. Randomize the magic square generation.) |
||
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. Note that it generates a randomized, though correct magic square. |
||
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 16: | Line 16: | ||
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 35: | Line 37: | ||
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²; |
||
my $ |
my $q = $n div 4; |
||
for |
for ^$q -> $r { |
||
for $ |
for $q ..^ $n - $q -> $c { |
||
my $ŕ = $n - 1 - $r; |
|||
my $ć = $n - 1 - $c; |
|||
(@sq[$ |
(@sq[$r;$c], @sq[$ŕ;$ć]) = (@sq[$ŕ;$ć], @sq[$r;$c]); |
||
(@sq[ |
(@sq[$c;$r], @sq[$ć;$ŕ]) = (@sq[$ć;$ŕ], @sq[$c;$r]); |
||
} |
} |
||
} |
} |
||
Line 48: | 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 $h = $n div 2; |
my $h = $n div 2; |
||
my $q = $n div 4; |
|||
gen-sq($h); |
gen-sq($h); |
||
$i *= 4; |
$i *= 4; |
||
for ^$h -> $r { |
for ^$h -> $r { |
||
for ^$h -> $c { |
for ^$h -> $c { |
||
@sq[$r + $h;$c] = @sq[$r;$c] + $h² * 3; |
@sq[$r + $h; $c] = @sq[$r;$c] + $h² * 3; |
||
@sq[$r;$c + $h] = @sq[$r;$c] + $h² * 2; |
@sq[$r; $c + $h] = @sq[$r;$c] + $h² * 2; |
||
@sq[$r + $h;$c + $h] = @sq[$r;$c] + $h²; |
@sq[$r + $h; $c + $h] = @sq[$r;$c] + $h²; |
||
} |
} |
||
for ^ |
for ^$q -> $c { |
||
next if $c == 0 and $r == ($h-1) div 2; |
next if $c == 0 and $r == ($h-1) div 2; |
||
(@sq[$r |
(@sq[$r;$c], @sq[$r + $h;$c]) = (@sq[$r + $h;$c], @sq[$r;$c]); |
||
} |
} |
||
} |
} |
||
(@sq[ |
(@sq[$q;$q], @sq[$q+$h;$q]) = (@sq[$q+$h;$q], @sq[$q;$q]); |
||
(@sq[($h-1)/2+$h][($h-1)/2], @sq[($h-1)/2][($h-1)/2]); |
|||
if $h > 4 { |
if $h > 4 { |
||
for ^$h -> $r { |
for ^$h -> $r { |
||
for ($n - |
for ($n - $q + 1) ..^ $n -> $c { |
||
(@sq[$r][$c] |
(@sq[$r;$c], @sq[$r + $h;$c]) = (@sq[$r + $h;$c], @sq[$r;$c]); |
||
(@sq[$r + $h][$c], @sq[$r][$c]); |
|||
} |
} |
||
} |
} |