google / or-tools

Google's Operations Research tools:
https://developers.google.com/optimization/
Apache License 2.0
11.34k stars 2.14k forks source link

Killer Sudoku example missing AllDifferent(cage) condition #98

Closed jbum closed 9 years ago

jbum commented 9 years ago

The comments for the Python Killer Sudoku example mention that "No number appears more than once in a cage", but the constraints fail to implement this. This is not a problem for the example puzzle, but in modifying the code to run through a suite of test puzzles, I found several other puzzles that require this condition in order to have a single unique solution.

Replace line 86: solver.Add(solver.Sum([x[i[0] - 1, i[1] - 1] for i in cc]) == res)

with cage = [x[i[0] - 1, i[1] - 1] for i in cc] solver.Add(solver.Sum([cage]) == res) solver.Add(solver.AllDifferent(cage))

Here is an example Killer Sudoku puzzle that requires this constraint:

[[3, [[1, 1], [2, 1]]], [14, [[1, 2], [1, 3]]], [21, [[1, 4], [2, 4], [2, 5], [2, 6]]], [13, [[1, 5], [1, 6], [1, 7]]], [22, [[1, 8], [1, 9], [2, 9], [3, 9]]], [20, [[2, 2], [3, 1], [3, 2], [4, 1]]], [15, [[2, 3], [3, 3]]], [10, [[2, 7], [2, 8]]], [11, [[3, 4], [3, 5]]], [29, [[3, 6], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6]]], [12, [[3, 7], [3, 8]]], [14, [[4, 7], [5, 7], [6, 7]]], [31, [[4, 8], [4, 9], [5, 8], [5, 9], [6, 8], [6, 9]]], [31, [[5, 1], [5, 2], [5, 3], [5, 4], [5, 5], [5, 6]]], [18, [[6, 1], [7, 1], [7, 2], [8, 2]]], [27, [[6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [7, 6]]], [10, [[7, 3], [8, 3]]], [7, [[7, 4], [7, 5]]], [7, [[7, 7], [7, 8]]], [19, [[7, 9], [8, 9], [9, 8], [9, 9]]], [11, [[8, 1], [9, 1]]], [26, [[8, 4], [8, 5], [8, 6], [9, 4]]], [17, [[8, 7], [8, 8]]], [11, [[9, 2], [9, 3]]], [6, [[9, 5], [9, 6], [9, 7]]]]

lperron commented 9 years ago

Thanks.

I patched the example.