Sudoku solving example.
(Context ctx)
| 453 | /// Sudoku solving example. |
| 454 | /// </summary> |
| 455 | static void SudokuExample(Context ctx) |
| 456 | { |
| 457 | Console.WriteLine("SudokuExample"); |
| 458 | |
| 459 | // 9x9 matrix of integer variables |
| 460 | IntExpr[][] X = new IntExpr[9][]; |
| 461 | for (uint i = 0; i < 9; i++) |
| 462 | { |
| 463 | X[i] = new IntExpr[9]; |
| 464 | for (uint j = 0; j < 9; j++) |
| 465 | X[i][j] = (IntExpr)ctx.MkConst(ctx.MkSymbol("x_" + (i + 1) + "_" + (j + 1)), ctx.IntSort); |
| 466 | } |
| 467 | |
| 468 | // each cell contains a value in {1, ..., 9} |
| 469 | Expr[][] cells_c = new Expr[9][]; |
| 470 | for (uint i = 0; i < 9; i++) |
| 471 | { |
| 472 | cells_c[i] = new BoolExpr[9]; |
| 473 | for (uint j = 0; j < 9; j++) |
| 474 | cells_c[i][j] = ctx.MkAnd(ctx.MkLe(ctx.MkInt(1), X[i][j]), |
| 475 | ctx.MkLe(X[i][j], ctx.MkInt(9))); |
| 476 | } |
| 477 | |
| 478 | // each row contains a digit at most once |
| 479 | BoolExpr[] rows_c = new BoolExpr[9]; |
| 480 | for (uint i = 0; i < 9; i++) |
| 481 | rows_c[i] = ctx.MkDistinct(X[i]); |
| 482 | |
| 483 | // each column contains a digit at most once |
| 484 | BoolExpr[] cols_c = new BoolExpr[9]; |
| 485 | for (uint j = 0; j < 9; j++) |
| 486 | { |
| 487 | IntExpr[] column = new IntExpr[9]; |
| 488 | for (uint i = 0; i < 9; i++) |
| 489 | column[i] = X[i][j]; |
| 490 | |
| 491 | cols_c[j] = ctx.MkDistinct(column); |
| 492 | } |
| 493 | |
| 494 | // each 3x3 square contains a digit at most once |
| 495 | BoolExpr[][] sq_c = new BoolExpr[3][]; |
| 496 | for (uint i0 = 0; i0 < 3; i0++) |
| 497 | { |
| 498 | sq_c[i0] = new BoolExpr[3]; |
| 499 | for (uint j0 = 0; j0 < 3; j0++) |
| 500 | { |
| 501 | IntExpr[] square = new IntExpr[9]; |
| 502 | for (uint i = 0; i < 3; i++) |
| 503 | for (uint j = 0; j < 3; j++) |
| 504 | square[3 * i + j] = X[3 * i0 + i][3 * j0 + j]; |
| 505 | sq_c[i0][j0] = ctx.MkDistinct(square); |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | BoolExpr sudoku_c = ctx.MkTrue(); |
| 510 | foreach (BoolExpr[] t in cells_c) |
| 511 | sudoku_c = ctx.MkAnd(ctx.MkAnd(t), sudoku_c); |
| 512 | sudoku_c = ctx.MkAnd(ctx.MkAnd(rows_c), sudoku_c); |
nothing calls this directly
no test coverage detected