Skip to content

Commit b99749b

Browse files
authored
Merge pull request manwar#2899 from andemark/branch-for-challenge-089
ch-2.p6 simplified
2 parents e402b58 + 977f0f9 commit b99749b

File tree

1 file changed

+37
-12
lines changed
  • challenge-089/mark-anderson/raku

1 file changed

+37
-12
lines changed

challenge-089/mark-anderson/raku/ch-2.p6

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,56 @@
22
# With help from https://www.wikihow.com/Solve-a-Magic-Square
33
#
44

5-
use Scalar::History;
5+
=begin usage
6+
7+
raku ch-2.p6
8+
9+
[8 1 6]
10+
[3 5 7]
11+
[4 9 2]
12+
13+
raku ch-2.p6 17
14+
15+
[155 174 193 212 231 250 269 288 1 20 39 58 77 96 115 134 153]
16+
[173 192 211 230 249 268 287 17 19 38 57 76 95 114 133 152 154]
17+
[191 210 229 248 267 286 16 18 37 56 75 94 113 132 151 170 172]
18+
[209 228 247 266 285 15 34 36 55 74 93 112 131 150 169 171 190]
19+
[227 246 265 284 14 33 35 54 73 92 111 130 149 168 187 189 208]
20+
[245 264 283 13 32 51 53 72 91 110 129 148 167 186 188 207 226]
21+
[263 282 12 31 50 52 71 90 109 128 147 166 185 204 206 225 244]
22+
[281 11 30 49 68 70 89 108 127 146 165 184 203 205 224 243 262]
23+
[ 10 29 48 67 69 88 107 126 145 164 183 202 221 223 242 261 280]
24+
[ 28 47 66 85 87 106 125 144 163 182 201 220 222 241 260 279 9]
25+
[ 46 65 84 86 105 124 143 162 181 200 219 238 240 259 278 8 27]
26+
[ 64 83 102 104 123 142 161 180 199 218 237 239 258 277 7 26 45]
27+
[ 82 101 103 122 141 160 179 198 217 236 255 257 276 6 25 44 63]
28+
[100 119 121 140 159 178 197 216 235 254 256 275 5 24 43 62 81]
29+
[118 120 139 158 177 196 215 234 253 272 274 4 23 42 61 80 99]
30+
[136 138 157 176 195 214 233 252 271 273 3 22 41 60 79 98 117]
31+
[137 156 175 194 213 232 251 270 289 2 21 40 59 78 97 116 135]
32+
33+
=end usage
634

735
unit sub MAIN(UInt $n where * mod 2 = 3); #= a positive odd integer
836

937
.say for odd-magic-square($n);
1038

1139
sub odd-magic-square($n) {
12-
subset Valid of UInt where 0 <= * < $n;
13-
14-
my $r := Scalar::History.create(0, Valid);
15-
my $c := Scalar::History.create(($n / 2).floor, Valid);
1640
my @matrix = [0 xx $n] xx $n;
17-
@matrix[$r][$c] = 1;
41+
my $r = 1;
42+
my $c = ($n / 2).floor - 1;
1843

19-
for 2..($n**2) -> $num {
20-
try $r--; if $! { $r = $n - 1 }
21-
try $c++; if $! { $c = 0 }
44+
for 1..($n**2) -> $num {
45+
$r = ($r - 1) mod $n;
46+
$c = ($c + 1) mod $n;
2247

2348
if @matrix[$r][$c] {
24-
$r = $r.VAR.get-history.tail + 1;
25-
$c = $c.VAR.get-history.tail;
49+
$r = ($r + 1) mod $n + 1;
50+
$c = ($c - 1) mod $n;
2651
}
2752

2853
@matrix[$r][$c] = $num;
2954
}
3055

31-
@matrix.map(*.fmt("%{($n**2).chars}d").Array);
56+
@matrix.map(*.fmt( "%{ ($n**2).chars }d" ).Array);
3257
}

0 commit comments

Comments
 (0)