AddModuloEquaility 不适用于 python ORtools

问题描述 投票:0回答:1

我正在尝试解决一个依赖于行条目之和为 0 mod (n) 的问题。我尝试编写一个简化版本,但无法弄清楚如何使用 model.AddModuloEquality。例如,以下代码(改编自谷歌 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)
python constraints or-tools
1个回答
0
投票

它是

target = var % mod
add_modulo_equality(target, var, mod)

所以

add_modulo_equality(0, var, 12)

© www.soinside.com 2019 - 2024. All rights reserved.