The source code and dockerfile for the GSW2024 AI Lab.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

54 lines
1.5 KiB

2 months ago
  1. /* MAGIC, Magic Square */
  2. /* Written in GNU MathProg by Andrew Makhorin <mao@gnu.org> */
  3. /* In recreational mathematics, a magic square of order n is an
  4. arrangement of n^2 numbers, usually distinct integers, in a square,
  5. such that n numbers in all rows, all columns, and both diagonals sum
  6. to the same constant. A normal magic square contains the integers
  7. from 1 to n^2.
  8. (From Wikipedia, the free encyclopedia.) */
  9. param n, integer, > 0, default 4;
  10. /* square order */
  11. set N := 1..n^2;
  12. /* integers to be placed */
  13. var x{i in 1..n, j in 1..n, k in N}, binary;
  14. /* x[i,j,k] = 1 means that cell (i,j) contains integer k */
  15. s.t. a{i in 1..n, j in 1..n}: sum{k in N} x[i,j,k] = 1;
  16. /* each cell must be assigned exactly one integer */
  17. s.t. b{k in N}: sum{i in 1..n, j in 1..n} x[i,j,k] = 1;
  18. /* each integer must be assigned exactly to one cell */
  19. var s;
  20. /* the magic sum */
  21. s.t. r{i in 1..n}: sum{j in 1..n, k in N} k * x[i,j,k] = s;
  22. /* the sum in each row must be the magic sum */
  23. s.t. c{j in 1..n}: sum{i in 1..n, k in N} k * x[i,j,k] = s;
  24. /* the sum in each column must be the magic sum */
  25. s.t. d: sum{i in 1..n, k in N} k * x[i,i,k] = s;
  26. /* the sum in the diagonal must be the magic sum */
  27. s.t. e: sum{i in 1..n, k in N} k * x[i,n-i+1,k] = s;
  28. /* the sum in the co-diagonal must be the magic sum */
  29. solve;
  30. printf "\n";
  31. printf "Magic sum is %d\n", s;
  32. printf "\n";
  33. for{i in 1..n}
  34. { printf{j in 1..n} "%3d", sum{k in N} k * x[i,j,k];
  35. printf "\n";
  36. }
  37. printf "\n";
  38. end;