In a model Or-tools, how to return the value linked to the first boolean True?

34 Views Asked by At

enter image description here

In list, I have this kind of data in my model, a ortools boolean linked to a Knownvalue.

What is certain is when a boolean becomes True all those below will also be True

I want to return the KnownValue to the first boolean = 1, here in the example return 2.

How would you do it, while having better performance?

Thanks in advance,

1

There are 1 best solutions below

0
Laurent Perron On BEST ANSWER

you can use a min_equality constraint with some clever offset to compute the first position that is true. It will set the target to len(bool_vars) if none is true.

bool_vars = [...]

num_bool_vars = len(bool_vars)

first_true = model.NewIntVar(0, num_bool_vars + 1, 'first_true')

model.AddMinEquality(target_var,
                     [num_bool_vars - bool_vars[i] * (num_bool_vars - i)
                      for i in range(num_bool_vars)])

THen you can link this to you values with a simple element constraint.

Full example: https://github.com/google/or-tools/blob/main/ortools/sat/docs/channeling.md#computing-the-index-of-the-first-boolean-variable-set-to-true