0

I'm playing around with OR Tools, just wondering if there is any way to hold the number of times a certain constraint is satisfied?

In this case, I'd like to keep track of the number of times my 'diff' variable is -1, -2, 0, 2 , etc.

I've gotten the solution printer from the official documentation, so would I have to edit/tweak that in any way to return count as well?

Thanks in advance, I'm new to this.

from ortools.sat.python import cp_model
model = cp_model.CpModel()
x = model.NewIntVar(0, 10, 'x')
y = model.NewIntVar(0, 10, 'y')
diff = model.NewIntVar(-10,10,'diff')
model.Add(diff == x - y)
#occurences of each diff

#solution printer
class VarArraySolutionPrinter(cp_model.CpSolverSolutionCallback):
    """Print intermediate solutions."""

    def __init__(self, variables):
        cp_model.CpSolverSolutionCallback.__init__(self)
        self.__variables = variables
        self.__solution_count = 0

    def on_solution_callback(self):
        self.__solution_count += 1
        for v in self.__variables:
            print(f"{v}={self.Value(v)}", end=" ")
        print()

    def solution_count(self):
        return self.__solution_count

solver = cp_model.CpSolver()
# solver.parameters.log_search_progress = True
solution_printer = VarArraySolutionPrinter([x, y, diff])
solver.parameters.enumerate_all_solutions = True
status = solver.Solve(model, solution_printer)

1 Answer 1

1

Why don't you just increase a counter in the on_solution_callback() method ?

Sign up to request clarification or add additional context in comments.

1 Comment

yes ive just figured it out. this was very trivial, sorry for the trouble.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.