ocaml: phase 5.1 magic_square.ml baseline (5x5 Siamese, diag sum = 65)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Siamese construction for odd-order magic squares: - place 1 at (0, n/2) - for k = 2..n^2, move up-right with (x-1+n) mod n wrap - if the target cell is taken, drop down one row instead for n=5, magic constant = n*(n^2+1)/2 = 5*26/2 = 65 Returns the main-diagonal sum (65 by construction). Tests 2D array via Array.init + Array.make, mod arithmetic with the (x-1+n) mod n idiom for negative-safe wrap, nested begin/end branches inside for-loop body. 166 baseline programs total.
This commit is contained in:
@@ -81,6 +81,7 @@
|
||||
"lis.ml": 6,
|
||||
"list_ops.ml": 30,
|
||||
"luhn.ml": 2,
|
||||
"magic_square.ml": 65,
|
||||
"mat_mul.ml": 621,
|
||||
"matrix_power.ml": 832040,
|
||||
"max_path_tree.ml": 11,
|
||||
|
||||
27
lib/ocaml/baseline/magic_square.ml
Normal file
27
lib/ocaml/baseline/magic_square.ml
Normal file
@@ -0,0 +1,27 @@
|
||||
let n = 5
|
||||
|
||||
let make_magic () =
|
||||
let m = Array.init n (fun _ -> Array.make n 0) in
|
||||
let row = ref 0 in
|
||||
let col = ref (n / 2) in
|
||||
for k = 1 to n * n do
|
||||
m.(!row).(!col) <- k;
|
||||
let nr = (!row - 1 + n) mod n in
|
||||
let nc = (!col + 1) mod n in
|
||||
if m.(nr).(nc) <> 0 then begin
|
||||
row := (!row + 1) mod n
|
||||
end else begin
|
||||
row := nr;
|
||||
col := nc
|
||||
end
|
||||
done;
|
||||
m
|
||||
|
||||
;;
|
||||
|
||||
let m = make_magic () in
|
||||
let sum_diag = ref 0 in
|
||||
for i = 0 to n - 1 do
|
||||
sum_diag := !sum_diag + m.(i).(i)
|
||||
done;
|
||||
!sum_diag
|
||||
Reference in New Issue
Block a user