Magic squares/Raku: Difference between revisions
m
syntax highlighting
Thundergnat (talk | contribs) m (→{{header|Perl 6}}: Add links to the various tasks) |
Thundergnat (talk | contribs) m (syntax highlighting) |
||
(6 intermediate revisions by the same user not shown) | |||
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.
Invoke at the command line and pass in the desired size as a parameter.
Line 5 ⟶ 6:
See:<ul>
<li>[[Magic_squares_of_odd_order#
<li>[[Magic_squares_of_singly_even_order#
<li>[[Magic_squares_of_doubly_even_order#
</ul>
<syntaxhighlight lang="raku"
my @sq;
my $i = 1;
gen-sq($n);
Line 21 ⟶ 25:
multi sub gen-sq (2) { # invalid
note "Sorry, can not generate a 2 x 2 magic square." and exit;
}
multi sub gen-sq ($n where {$n % 2}) { # odd
my $x = $n/2;
my $y = 0;
@sq[($i % $n ?? $y-- !! $y++) % $n][($i % $n ?? $x++ !! $x) % $n] = $i++ for ^
}
multi sub gen-sq ($n where {$n %% 4}) { # doubly even
my $x = 0;
my $y = 0;
@sq[$i % $n ?? $y !! $y++][($i-1) % $n] = $i++ for ^
for
(@sq[
(@sq[$c;$r], @sq[$
(@sq[$n-1-$c;$n-1-$r], @sq[$c;$r]);▼
}
}
}
multi sub gen-sq ($n where {$n %% 2 and $n % 4}) { # singly even
▲ my $h = $n div 2;
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 ^
next if $c == 0 and $r == ($h-1) div 2;
(@sq[$r
}
(@sq[
▲ if $h > 4 {
}
}
}
}
}</
|