我正在尝试解决一个依赖于行条目之和为 0 mod (n) 的问题。我尝试编写一个简化版本,但无法弄清楚如何使用
model.AddModuloEquality
。例如,下面的代码(改编自 Google 的 Suduko 示例)应该给出数组 [[10,14][11,13]]。有用。如果我添加约束,它应该是 24,但如果我尝试使其等于 0 mod 12,则不应该是相同的答案? 第一天使用 ORtools,并暂时离开 Python。
from ortools.sat.python import cp_model
def basic_mod(rows,columns, mod=None):
# Create the model.
model = cp_model.CpModel()
ay=[]
rows = rows
cols=columns
row = list(range(0, rows))
col= list(range(0,cols))
mod=mod
#create vars
grid = {}
for i in row:
for j in col:
grid[(i, j)] = model.new_int_var(10,14, "grid %i %i" % (i, j))
#constraints
# no repeats in row
for i in row:
model.add_all_different(grid[(i, j)] for j in col)
# # no repeats in column
for j in col:
model.add_all_different(grid[(i, j)] for i in row)
#sum of row
for i in row:
sum_of_row_vars = sum(grid[(i, j)] for j in col)
#model.Add(sum_of_row_vars == 24)
model.AddModuloEquality(sum_of_row_vars, 0,12)
# No repeats in whole array.
#add a variable to each cell
array = []
for i in row:
for j in col:
array.append(grid[(i, j)])
model.add_all_different(array)
# Solves and prints out the FIRST solution.
solver = cp_model.CpSolver()
status = solver.solve(model)
if status == cp_model.OPTIMAL:
for i in row:
print([int(solver.value(grid[(i, j)])) for j in col])
ay.append([int(solver.value(grid[(i, j)])) for j in col])
else:
print("no solution")
return ay
rows=2
cols=2
mod=12
basic_mod(rows,cols,mod)
它是
target = var % mod
add_modulo_equality(target, var, mod)
所以
add_modulo_equality(0, var, 12)
这是一个工作代码:
from ortools.sat.python import cp_model
def basic_mod(rows,columns, mod=None):
# Create the model.
model = cp_model.CpModel()
ay=[]
rows = rows
cols=columns
row = list(range(0, rows))
col= list(range(0,cols))
mod=mod
#create vars
grid = {}
for i in row:
for j in col:
grid[(i, j)] = model.new_int_var(10,14, "grid %i %i" % (i, j))
#constraints
# no repeats in row
for i in row:
model.add_all_different(grid[(i, j)] for j in col)
# # no repeats in column
for j in col:
model.add_all_different(grid[(i, j)] for i in row)
#sum of row
for i in row:
sum_of_col: cp_model.IntVar = model.new_int_var(0, cols * 14, f'sum_{i}')
model.add(sum_of_col == sum(grid[(i, j)] for j in col) )
model.add_modulo_equality(0, sum_of_col, 12)
# No repeats in whole array.
#add a variable to each cell
array = []
for i in row:
for j in col:
array.append(grid[(i, j)])
model.add_all_different(array)
# Solves and prints out the FIRST solution.
solver = cp_model.CpSolver()
solver.parameters.log_search_progress = True
status = solver.solve(model)
if status == cp_model.OPTIMAL:
for i in row:
print([int(solver.value(grid[(i, j)])) for j in col])
ay.append([int(solver.value(grid[(i, j)])) for j in col])
else:
print("no solution")
return ay
rows=2
cols=2
mod=12
basic_mod(rows,cols,mod)
显示
[14, 10]
[13, 11]