Anonymous user
Magic squares of singly even order: Difference between revisions
→{{header|Rust}}: Optimization (mut removed)
(→{{header|rust}}: Rust version) |
(→{{header|Rust}}: Optimization (mut removed)) |
||
Line 1,584:
fn main() {
let
match env::args().nth(1).and_then(|arg| arg.parse().ok()).ok_or(
"Please specify the size of the magic square, as a positive multiple of 4 plus 2.",▼
▲ "Please specify the size of the magic square, as a positive multiple of 4 plus 2."
Ok(arg) if arg % 2 == 1 || arg >= 6 && (arg - 2) % 4 == 0 => arg,
);▼
_ => panic!("Argument must be a positive multiple of 4 plus 2."),▼
▲ "Argument must be a positive multiple of 4 plus 2."
);▼
let (ms, mc) = magic_square_singly_even(n);
println!("n: {}", n);
println!("Magic constant: {}\n", mc);
let width = (n * n).to_string().len() + 1;
Line 1,602 ⟶ 1,601:
print!("{e:>w$}", e = elem, w = width);
}
println!(
}
}
fn magic_square_singly_even(n:
let size = n * n;
let half = n / 2;
let sub_square_size = size / 4;
let sub_square = magic_square_odd(half);
let quadrant_factors =
for r in 0..n {▼
for c in 0..n {▼
let quadrant = (r / half) * 2 + (c / half);▼
ms[r as usize][c as usize] = sub_square[(r % half) as usize][(c % half) as usize];▼
ms[r as usize][c as usize] += quadrant_factors[quadrant as usize] * sub_square_size;▼
}▼
let cols_left = half / 2;
let cols_right = cols_left - 1;
r + half
▲ };
.collect()
.collect::<Vec<Vec<_>>>();
(ms, (n * n + 1) * n / 2)
}
fn magic_square_odd(n:
n * (((c + 1) + (r + 1) - 1 + (n >> 1)) % n)
▲ i = n - 1;
▲ j -= 2;
▲ i += 1;
▲ continue;
}</lang>
{{out}}
<pre>
n: 6
Magic constant: 111
n: 10
Magic constant: 505
17
24
n: 18
Magic constant: 2925
290 300 310 320 6 16 26 36 37 209 219 229 239 168 178 107 117 118
301 311 321 250 17 27 28 38 48 220 230 240 169 179 189 109 119 129
312 322 251 261 19 29 39 49 59 231 241 170 180 181 191 120 130 140
323 252 253 263 30 40 50 60 70 242 171 172 182 192 202 131 141 151
1 254 264 274 284 51 61 71 81 163 173 183 193 203 213 142 152 162
255 265 275 285 52 62 72 73 2 174 184 194 204 214 224 153 154 83
266 276 286 296 63 64 74 3 13 185 195 205 215 225 226 155 84 94
277 287 297 298 65 75 4 14 24 196 206 216 217 227 237 85 95 105
288 289 299 309 76 5 15 25 35 207 208 218 228 238 167 96 106 116
47 57 67 77 249 259 269 279 280 128 138 148 158 87 97 188 198 199
58 68 78 7 260 270 271 281 291 139 149 159 88 98 108 190 200 210
69 79 8 18 262 272 282 292 302 150 160 89 99 100 110 201 211 221
80 9 10 20 273 283 293 303 313 161 90 91 101 111 121 212 222 232
244 11 21 31 41 294 304 314 324 82 92 102 112 122 132 223 233 243
12 22 32 42 295 305 315 316 245 93 103 113 123 133 143 234 235 164
23 33 43 53 306 307 317 246 256 104 114 124 134 144 145 236 165 175
34 44 54 55 308 318 247 257 267 115 125 135 136 146 156 166 176 186
45 46 56 66 319 248 258 268 278 126 127 137 147 157 86 177 187 197
</pre>
=={{header|zkl}}==
{{trans|Java}}
|