실습 코드
from ortools.sat.python import cp_model
# ------------------ Day3(25.06.12) ------------------
class SolutionPrinter(cp_model.CpSolverSolutionCallback):
def __init__(self, variables):
cp_model.CpSolverSolutionCallback.__init__(self)
self.variables = variables
self.solution_count = 0
def OnSolutionCallback(self):
self.solution_count += 1
print(f'Solution {self.solution_count}:', [self.Value(var) for var in self.variables])
model = cp_model.CpModel()
# x, y, z는 1~4 사이 정수
x = model.NewIntVar(1, 4, 'x')
y = model.NewIntVar(1, 4, 'y')
z = model.NewIntVar(1, 4, 'z')
# 세 변수는 서로 다름
model.AddAllDifferent([x, y, z])
# 세 변수 합이 6 이하
model.Add(x + y + z <= 6)
# 솔버 생성
solver = cp_model.CpSolver()
status = solver.Solve(model)
# 출력(콜백을 이용하면 여러 해를 한 번에 출력할 수 있음)
solution_printer = SolutionPrinter([x, y, z])
solver.SearchForAllSolutions(model, solution_printer)
'''
Solution 1: [3, 1, 2]
Solution 2: [2, 1, 3]
Solution 3: [1, 2, 3]
Solution 4: [1, 3, 2]
Solution 5: [3, 2, 1]
Solution 6: [2, 3, 1]
'''