Advertisement
Guest User

Untitled

a guest
Mar 28th, 2021
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.29 KB | None | 0 0
  1. # C'est un homme qui rentre dans un bar et qui dit: "hey les gars c'est moi !", mais en fait, c'était pas lui...
  2. from ortools.sat.python import cp_model
  3.  
  4. class VarArraySolutionPrinter(cp_model.CpSolverSolutionCallback):
  5.     #Print intermediate solutions.
  6.  
  7.     def __init__(self, variables):
  8.         cp_model.CpSolverSolutionCallback.__init__(self)
  9.         self.__variables = variables
  10.         self.__solution_count = 0
  11.  
  12.     def on_solution_callback(self):
  13.         self.__solution_count += 1
  14.         for v in self.__variables:
  15.             print('%s=%i' % (v, self.Value(v)), end=' ')
  16.         print()
  17.  
  18.     def solution_count(self):
  19.         return self.__solution_count
  20.  
  21. def GetEquation(w, LETTERS, letters, BASE):
  22.     LEN_W = len(w)
  23.     equation = []
  24.     for i, l in enumerate(w):
  25.         equation.append(letters[LETTERS.index(l)] * BASE **(LEN_W-i))
  26.     equation = sum(equation)
  27.     return equation
  28.  
  29.    
  30. # OUIIII ya 3 mots mais on pourrait faire avec une demi infinitée
  31. def LinearProgrammingV8_500CC(w1, w2, w3):
  32.     BASE = 10
  33.     LETTERS = list(set(w1 + w2 + w3))
  34.     FIRST_LETTERS = [w1[0], w2[0], w3[0]]
  35.     LEN_W1 = len(w1)
  36.     LEN_W2 = len(w2)
  37.     LEN_W3 = len(w3)
  38.    
  39.     model = cp_model.CpModel()
  40.  
  41.     letters = []
  42.     for l in LETTERS:
  43.         if(l in FIRST_LETTERS):
  44.             # si la lettre apparait en premier, elle est pas égale à 0 et ca nous évite bcp de merdes, mais ca change rien en vrai c'est même pas défini dans la regle
  45.             letters.append(model.NewIntVar(1, BASE - 1, l))
  46.         else:
  47.             letters.append(model.NewIntVar(0, BASE - 1, l))
  48.        
  49.     # Define constraints.
  50.     model.AddAllDifferent(letters)
  51.    
  52.    
  53.     equation1 = GetEquation(w1, LETTERS, letters, BASE)
  54.     equation2 = GetEquation(w2, LETTERS, letters, BASE)
  55.     equation3 = GetEquation(w3, LETTERS, letters, BASE)
  56.  
  57.     model.Add(equation1 + equation2 == equation3)
  58.     print(equation1)
  59.     print(equation2)
  60.     print(equation3)
  61.  
  62.     # Solve model.
  63.     solver = cp_model.CpSolver()
  64.     solution_printer = VarArraySolutionPrinter(letters)
  65.     status = solver.SearchForAllSolutions(model, solution_printer)
  66.     solver.solutions()
  67.     print('  - solutions found : %i' % solution_printer.solution_count())
  68.  
  69. LinearProgrammingV8_500CC("ROUGE", "FRUIT", "CERISE")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement