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.

84 lines
2.5 KiB

2 months ago
  1. /* SUDOKU, Number Placement Puzzle */
  2. /* Written in GNU MathProg by Andrew Makhorin <mao@gnu.org> */
  3. /* Sudoku, also known as Number Place, is a logic-based placement
  4. puzzle. The aim of the canonical puzzle is to enter a numerical
  5. digit from 1 through 9 in each cell of a 9x9 grid made up of 3x3
  6. subgrids (called "regions"), starting with various digits given in
  7. some cells (the "givens"). Each row, column, and region must contain
  8. only one instance of each numeral.
  9. Example:
  10. +-------+-------+-------+
  11. | 5 3 . | . 7 . | . . . |
  12. | 6 . . | 1 9 5 | . . . |
  13. | . 9 8 | . . . | . 6 . |
  14. +-------+-------+-------+
  15. | 8 . . | . 6 . | . . 3 |
  16. | 4 . . | 8 . 3 | . . 1 |
  17. | 7 . . | . 2 . | . . 6 |
  18. +-------+-------+-------+
  19. | . 6 . | . . . | 2 8 . |
  20. | . . . | 4 1 9 | . . 5 |
  21. | . . . | . 8 . | . 7 9 |
  22. +-------+-------+-------+
  23. (From Wikipedia, the free encyclopedia.) */
  24. param givens{1..9, 1..9}, integer, >= 0, <= 9, default 0;
  25. /* the "givens" */
  26. var x{i in 1..9, j in 1..9, k in 1..9}, binary;
  27. /* x[i,j,k] = 1 means cell [i,j] is assigned number k */
  28. s.t. fa{i in 1..9, j in 1..9, k in 1..9: givens[i,j] != 0}:
  29. x[i,j,k] = (if givens[i,j] = k then 1 else 0);
  30. /* assign pre-defined numbers using the "givens" */
  31. s.t. fb{i in 1..9, j in 1..9}: sum{k in 1..9} x[i,j,k] = 1;
  32. /* each cell must be assigned exactly one number */
  33. s.t. fc{i in 1..9, k in 1..9}: sum{j in 1..9} x[i,j,k] = 1;
  34. /* cells in the same row must be assigned distinct numbers */
  35. s.t. fd{j in 1..9, k in 1..9}: sum{i in 1..9} x[i,j,k] = 1;
  36. /* cells in the same column must be assigned distinct numbers */
  37. s.t. fe{I in 1..9 by 3, J in 1..9 by 3, k in 1..9}:
  38. sum{i in I..I+2, j in J..J+2} x[i,j,k] = 1;
  39. /* cells in the same region must be assigned distinct numbers */
  40. /* there is no need for an objective function here */
  41. solve;
  42. for {i in 1..9}
  43. { for {0..0: i = 1 or i = 4 or i = 7}
  44. printf " +-------+-------+-------+\n";
  45. for {j in 1..9}
  46. { for {0..0: j = 1 or j = 4 or j = 7} printf(" |");
  47. printf " %d", sum{k in 1..9} x[i,j,k] * k;
  48. for {0..0: j = 9} printf(" |\n");
  49. }
  50. for {0..0: i = 9}
  51. printf " +-------+-------+-------+\n";
  52. }
  53. data;
  54. /* These data correspond to the example above. */
  55. param givens : 1 2 3 4 5 6 7 8 9 :=
  56. 1 5 3 . . 7 . . . .
  57. 2 6 . . 1 9 5 . . .
  58. 3 . 9 8 . . . . 6 .
  59. 4 8 . . . 6 . . . 3
  60. 5 4 . . 8 . 3 . . 1
  61. 6 7 . . . 2 . . . 6
  62. 7 . 6 . . . . 2 8 .
  63. 8 . . . 4 1 9 . . 5
  64. 9 . . . . 8 . . 7 9 ;
  65. end;