pythonboolean-logicor-toolsconstraint-programmingcp-sat

OR-Tools CP-SAT conditional constraint


In the problem I am trying to solve, I have a list of length n of boolean variables called x. Given an integer m where m < n, I need to define these two constraints:

From what I've read I should use one or several of the following:

However, after a few hours of trying I could not figure it out. Any help to solve this is very much appreciated!


Solution

  •   model.add_at_most_one(x)
    

    This is the only working case if I am not mistaken.

    Now, the medium answer for one of the constraint:

       model.add(sum(x[:m] == 0).only_enforce_if(x[m])
    

    and finally the general one (still for one of the constraints):

       is_positive_before_m = model.new_bool_var('')
    
       # is_positive_before_m <=> sum(x[:m]) >= 0
       model.add(sum(x[:m]) >= 0).only_enforce_if(is_positive_before_m)
       model.add(sum(x[:m]) == 0).only_enforce_if(~is_positive_before_m)
    
       # is_positive_before_m => sum(x[m:]) == 0
       model.add(sum(x[m:] == 0).only_enforce_if(is_positive_before_m)