Magic squares/Raku: Difference between revisions

m
→‎{{header|Perl 6}}: Clean up and refactor a bit. Randomize the magic square generation.
(→‎{{header|Perl 6}}: Add a few comments)
m (→‎{{header|Perl 6}}: Clean up and refactor a bit. Randomize the magic square generation.)
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. Note that it generates a randomized, though correct magic square.
Invoke at the command line and pass in the desired size as a parameter.
 
Line 16:
gen-sq($n);
 
my @r = ^$n .pick(*);
say .fmt("%{$i.chars}d", ' ') for @sq;
 
say $_[@r].fmt("%{$i.chars}d", ' ') for @sq.pick(*);
 
say "\nThe magic number is ", [+] @sq[0].list;
Line 35 ⟶ 37:
my $y = 0;
@sq[$i % $n ?? $y !! $y++][($i-1) % $n] = $i++ for ^$n²;
my $tq = $n div 4;
for 0 ..^ $n div 4q -> $r {
for $n div 4q ..^ $n - $n div 4q -> $c {
(@sq[$r;my $c],ŕ = @sq[$n - 1 - $r;$n-1-$c]) =
(@sq[my $n-1-$r;ć = $n - 1 -$c], @sq[$r;$c]);
(@sq[$cr;$rc], @sq[$n-1-ŕ;$cć]) = (@sq[$ŕ;$n-1-ć], @sq[$r;$c]) =;
(@sq[$n-1-$c;$n-1-$r], @sq[$ć;$ŕ]) = (@sq[$ć;$ŕ], @sq[$c;$r]);
}
}
Line 48 ⟶ 50:
multi sub gen-sq ($n where {$n %% 2 and $n % 4}) { # singly even
my $h = $n div 2;
my $q = $n div 4;
gen-sq($h);
$i *= 4;
for ^$h -> $r {
for ^$h -> $c {
@sq[$r + $h; $c] = @sq[$r;$c] + $h² * 3;
@sq[$r; $c + $h] = @sq[$r;$c] + $h² * 2;
@sq[$r + $h; $c + $h] = @sq[$r;$c] + $h²;
}
for ^(($h-1)/2)q -> $c {
next if $c == 0 and $r == ($h-1) div 2;
(@sq[$r][;$c], @sq[$r + $h][;$c]) = (@sq[$r + $h][;$c], @sq[$r][;$c]);
}
}
(@sq[($h-1)/2][(q;$h-1)/2q], @sq[($q+$h-1;$q])/2 = (@sq[$q+$h;$q], @sq[($h-1)/2q;$q]) =;
(@sq[($h-1)/2+$h][($h-1)/2], @sq[($h-1)/2][($h-1)/2]);
if $h > 4 {
for ^$h -> $r {
for ($n - ($h-3)q /+ 21) ..^ $n -> $c {
(@sq[$r;$c], @sq[$r + $h;$c],) = (@sq[$r + $h;$c], @sq[$r;$c]) =;
(@sq[$r + $h][$c], @sq[$r][$c]);
}
}
10,327

edits