Beispiel #1
0
def main(problem):

  model = cp.CpModel()

  # data
  n = len(problem[0][0]) # number of digits
  
  # decision variabels
  x = [model.NewIntVar(0,9,f"x[{i}]") for i in range(n)]

  # constraints
  for digits, num_correct_pos, num_correct_number in problem:
    check(model, digits, x, num_correct_pos, num_correct_number)

  # search and solution
  solver  = cp.CpSolver()
  solution_printer = ListPrinter(x)
  status = solver.SearchForAllSolutions(model, solution_printer)
  if not status in [cp.OPTIMAL, cp.FEASIBLE]:
    print("No solution!")

  print()
  print("NumSolutions:", solution_printer.SolutionCount())  
  print("NumConflicts:", solver.NumConflicts())
  print("NumBranches:", solver.NumBranches())
  print("WallTime:", solver.WallTime())
  print()
Beispiel #2
0
def main(k=8, num_sol=0):

    model = cp.CpModel()

    #
    # data
    #
    print("k:", k)

    if not (k % 4 == 0 or k % 4 == 3):
        print("There is no solution for K unless K mod 4 == 0 or K mod 4 == 3")
        return
    p = list(range(2 * k))

    #
    # declare variables
    #
    position = [model.NewIntVar(0, 2 * k - 1, "position[%i]" % i) for i in p]
    solution = [model.NewIntVar(1, k, "position[%i]" % i) for i in p]

    #
    # constraints
    #
    model.AddAllDifferent(position)

    for i in range(1, k + 1):
        model.Add(position[i + k - 1] == position[i - 1] + i + 1)
        model.AddElement(position[i - 1], solution, i)
        model.AddElement(position[k + i - 1], solution, i)

    # symmetry breaking
    model.Add(solution[0] < solution[2 * k - 1])

    #
    # search and result
    #
    solver = cp.CpSolver()

    # Activating these makes it faster for small numbers but
    # slower on larger numbers.
    # solver.parameters.search_branching = cp.PORTFOLIO_SEARCH
    # solver.parameters.cp_model_presolve = False
    # solver.parameters.linearization_level = 0
    # solver.parameters.cp_model_probing_level = 0

    # status = solver.Solve(model)
    solution_printer = ListPrinter(solution, num_sol)
    # solution_printer = SimpleSolutionCounter(solution) # count sols
    status = solver.SearchForAllSolutions(model, solution_printer)
    print("status:", solver.StatusName(status))

    if status != cp.OPTIMAL and status != cp.FEASIBLE:
        print("No solution")

    print()
    print("NumSolutions:", solution_printer.SolutionCount())
    print("NumConflicts:", solver.NumConflicts())
    print("NumBranches:", solver.NumBranches())
    print("WallTime:", solver.WallTime())
Beispiel #3
0
def main():

    model = cp.CpModel()

    #
    # data
    #
    family = [1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 4, 4]
    n = len(family)

    #
    # declare variables
    #
    x = [model.NewIntVar(0, n - 1, 'x[%i]' % i) for i in range(n)]

    #
    # constraints
    #
    model.AddAllDifferent(x)

    # Can't be one own's Secret Santa
    # Ensure that there are no fix-point in the array
    for i in range(n):
        model.Add(x[i] != i)

    # No Secret Santa to a person in the same family
    for i in range(n):
        val = model.NewIntVar(min(family), max(family), "val")
        model.AddElement(x[i], family, val)
        model.Add(val != family[i])

    #
    # solution and search
    #
    solver = cp.CpSolver()
    # solver.parameters.search_branching = cp.PORTFOLIO_SEARCH
    # solver.parameters.cp_model_presolve = False
    # solver.parameters.linearization_level = 0
    # solver.parameters.cp_model_probing_level = 0

    solution_printer = ListPrinter(x)
    # solution_printer = SimpleSolutionCounter(x)
    status = solver.SearchForAllSolutions(model, solution_printer)

    if not (status == cp.OPTIMAL or status == cp.FEASIBLE):
        print("No solution!")

    print('NumSolutions:', solution_printer.SolutionCount())
    print('NumConflicts:', solver.NumConflicts())
    print('NumBranches:', solver.NumBranches())
    print('WallTime:', solver.WallTime())
Beispiel #4
0
def main():

    model = cp.CpModel()

    #
    # data
    #
    Belgium = 0
    Denmark = 1
    France = 2
    Germany = 3
    Netherlands = 4
    Luxembourg = 5

    n = 6
    max_num_colors = 4

    # declare variables
    color = [model.NewIntVar(1, max_num_colors, "x%i" % i) for i in range(n)]

    #
    # constraints
    #
    model.Add(color[Belgium] == 1)  # Symmetry breaking
    model.Add(color[France] != color[Belgium])
    model.Add(color[France] != color[Luxembourg])
    model.Add(color[France] != color[Germany])
    model.Add(color[Luxembourg] != color[Germany])
    model.Add(color[Luxembourg] != color[Belgium])
    model.Add(color[Belgium] != color[Netherlands])
    model.Add(color[Belgium] != color[Germany])
    model.Add(color[Germany] != color[Netherlands])
    model.Add(color[Germany] != color[Denmark])

    #
    # solution and search
    #
    solver = cp.CpSolver()
    solution_printer = ListPrinter(color)
    status = solver.SearchForAllSolutions(model, solution_printer)

    if not (status == cp.OPTIMAL or status == cp.FEASIBLE):
        print("No solutions found")

    print()
    print("NumSolutions:", solution_printer.SolutionCount())
    print("NumConflicts:", solver.NumConflicts())
    print("NumBranches:", solver.NumBranches())
    print("WallTime:", solver.WallTime())
Beispiel #5
0
def main():

    model = cp.CpModel()

    # data
    m = 32
    n = 8
    # Note: this is 1-based for compatibility (and lazyness)
    graph = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 5], [2, 6], [3, 2],
             [3, 4], [3, 6], [3, 7], [4, 1], [4, 3], [4, 6], [4, 7], [5, 2],
             [5, 3], [5, 6], [5, 8], [6, 2], [6, 3], [6, 4], [6, 5], [6, 7],
             [6, 8], [7, 3], [7, 4], [7, 6], [7, 8], [8, 5], [8, 6], [8, 7]]

    # declare variables
    x = [model.NewIntVar(1, n, "x%i" % i) for i in range(n)]

    #
    # constraints
    #
    model.AddAllDifferent(x)
    for i in range(m):
        # Note: make 0-based
        # model.Add(abs(x[graph[i][0] - 1] - x[graph[i][1] - 1]) > 1)
        diff = model.NewIntVar(-n, n, "d")
        model.Add(diff == x[graph[i][0] - 1] - x[graph[i][1] - 1])
        diff_abs = model.NewIntVar(-n, n, "d")
        model.AddAbsEquality(diff_abs, diff)
        model.Add(diff_abs > 1)

    # symmetry breaking
    model.Add(x[0] < x[n - 1])

    #
    # solution and search
    #
    solver = cp.CpSolver()
    solution_printer = ListPrinter(x)
    status = solver.SearchForAllSolutions(model, solution_printer)

    if not (status == cp.FEASIBLE or status == cp.OPTIMAL):
        print("No solution!")

    print()
    print("NumSolutions:", solution_printer.SolutionCount())
    print("NumConflicts:", solver.NumConflicts())
    print("NumBranches:", solver.NumBranches())
    print("WallTime:", solver.WallTime())
    print()
def main(n=7):
    model = cp.CpModel()

    x = [model.NewIntVar(0, n-1, 'x%i' % i) for i in range(n)]

    alldifferent_except_0(model, x)

    # Require that there should be exactly 2 0s.
    # z = model.NewIntVar(0,n-1,'z')
    # count_vars(model,x, 0, z)
    # model.Add(z == 2)
    # Simpler:
    count_vars(model,x, 0, 2)


    # model.AddDecisionStrategy(x, 
    #                          cp.CHOOSE_MIN_DOMAIN_SIZE,
    #                          # cp.CHOOSE_FIRST,
    #                          cp.SELECT_LOWER_HALF
    #                          # cp.SELECT_MIN_VALUE
    #                        )
    
 
    solver = cp.CpSolver()
    # solver.parameters.search_branching = cp.FIXED_SEARCH
    # solver.parameters.search_branching = cp.AUTOMATIC_SEARCH

    # These speeds things up:
    solver.parameters.search_branching = cp.PORTFOLIO_SEARCH
    solver.parameters.cp_model_presolve=False
    # solver.parameters.linearization_level = 0
    # solver.parameters.cp_model_probing_level = 0

    # flat = x 
    # flat.append(z)
    solution_printer = ListPrinter(x)
    # solution_printer = SimpleSolutionCounter(x)
    status = solver.SearchForAllSolutions(model, solution_printer)
    print('Solutions found : %i' % solution_printer.SolutionCount())
    # status = solver.Solve(model)
    # if status == cp.FEASIBLE or status == cp.OPTIMAL:
    #     print([int(solver.Value(x[i])) for i in range(n)])

    print('Statistics:')
    print('  - conflicts : %i' % solver.NumConflicts())
    print('  - branches  : %i' % solver.NumBranches())
    print('  - wall time : %f s' % solver.WallTime())
def main(base=10):

    model = cp.CpModel()

    # data
    print('base:', base)

    # declare variables
    s = model.NewIntVar(0, base - 1, 's')
    e = model.NewIntVar(0, base - 1, 'e')
    n = model.NewIntVar(0, base - 1, 'n')
    d = model.NewIntVar(0, base - 1, 'd')
    m = model.NewIntVar(0, base - 1, 'm')
    o = model.NewIntVar(0, base - 1, 'o')
    r = model.NewIntVar(0, base - 1, 'r')
    y = model.NewIntVar(0, base - 1, 'y')

    x = [s, e, n, d, m, o, r, y]

    #
    # constraints
    #
    model.AddAllDifferent(x)
    model.Add(
        s * base**3 + e * base**2 + n * base + d + m * base**3 + o * base**2 +
        r * base + e == m * base**4 + o * base**3 + n * base**2 + e * base +
        y, )
    model.Add(s > 0)
    model.Add(m > 0)

    #
    # solution and search
    #
    solver = cp.CpSolver()
    solution_printer = ListPrinter(x)
    status = solver.SearchForAllSolutions(model, solution_printer)

    if status != cp.OPTIMAL:
        print("No solution!")

    print()
    print('NumSolutions:', solution_printer.SolutionCount())
    print('NumConflicts:', solver.NumConflicts())
    print('NumBranches:', solver.NumBranches())
    print('WallTime:', solver.WallTime())
    print()
Beispiel #8
0
def main():

    model = cp.CpModel()

    #
    # data
    #
    n = 10

    #
    # declare variables
    #
    Vars = [model.NewIntVar(1, n, 'Vars[%i]' % i) for i in range(n)]
    X1, X2, X3, X4, X5, X6, X7, X8, X9, X10 = Vars

    #
    # constraints
    #
    model.AddAllDifferent(Vars)

    model.Add(X1 == 3)
    minus(model, X2, X3, X1)
    minus(model, X4, X5, X2)
    minus(model, X5, X6, X3)
    minus(model, X7, X8, X4)
    minus(model, X8, X9, X5)
    minus(model, X9, X10, X6)

    #
    # solution and search
    #
    solver = cp.CpSolver()
    solution_printer = ListPrinter(Vars)
    _status = solver.SearchForAllSolutions(model, solution_printer)

    # if status == cp.OPTIMAL:
    #  print('Vars:', [solver.Value(Vars[i]) for i in range(n)])

    print()
    print('NumSolutions:', solution_printer.SolutionCount())
    print('NumConflicts:', solver.NumConflicts())
    print('NumBranches:', solver.NumBranches())
    print('WallTime:', solver.WallTime())
Beispiel #9
0
def main(n, use_all_diff=1, print_sols=1):
    model = cp.CpModel()
    queens = [model.NewIntVar(0, n - 1, f'x{i}') for i in range(n)]

    model.AddAllDifferent(queens)
    if use_all_diff == 1:
        print("Use All Different")
        for i in range(n):
            diag1 = []
            diag2 = []
            for j in range(n):
                q1 = model.NewIntVar(0, 2 * n, f'diag1_{i}')
                diag1.append(q1)
                model.Add(q1 == queens[j] + j)
                q2 = model.NewIntVar(-n, n, f'diag2_{i}')
                diag2.append(q2)
                model.Add(q2 == queens[j] - j)
            model.AddAllDifferent(diag1)
            model.AddAllDifferent(diag2)
    else:
        # Alternative (naive) model (see nqueens.py)
        print("Use Naive")
        for i in range(n):
            for j in range(i):
                model.Add(queens[i] != queens[j])
                model.Add(queens[i] + i != queens[j] + j)
                model.Add(queens[i] - i != queens[j] - j)

    # print("model:", model) # Show the model

    solver = cp.CpSolver()

    # solution_printer = DiagramPrinter(queens) # Nicer output
    solution_printer = ListPrinter(queens)  # List of integers
    if print_sols != 1:
        solution_printer = SimpleSolutionCounter(
            queens)  # Just count solutions
    _ = solver.SearchForAllSolutions(model, solution_printer)
    print()
    print('Solutions found : %i' % solution_printer.SolutionCount())
    print()
    # print(solver.ResponseStats())
    print("WallTime:", solver.WallTime())
Beispiel #10
0
def main():

  model = cp.CpModel()

  # data
  n = 4
  base = 10

  # declare variables
  x = [model.NewIntVar(0, n - 1, "x%i" % i) for i in range(n)]
  y = model.NewIntVar(0, 10**n - 1, "y")

  #
  # constraints
  #
  # solver.Add(solver.AllDifferent([x[i] for i in range(n)]))
  model.AddAllDifferent(x)
  # solver.Add(x[0] > 0) # just for fun

  toNum(model, x, y, base)

  #
  # solution and search
  #
  solver = cp.CpSolver()
  all = x 
  all.append(y)
  # solution_printer = SimpleSolutionPrinter(all)
  solution_printer = ListPrinter(all)
  status = solver.SearchForAllSolutions(model, solution_printer)

  if status != cp.OPTIMAL:
    print("No solution!")

  print()
  print("NumSolutions", solution_printer.SolutionCount())
  print("NumConflicts:", solver.NumConflicts())
  print("NumBranches:", solver.NumBranches())
  print("WallTime:", solver.WallTime())
Beispiel #11
0
def main(n=5):

    model = cp.CpModel()

    # data
    print("n:", n)

    # declare variables
    # Note: domain should be 0..n-1
    x = [model.NewIntVar(0, n - 1, "x%i" % i) for i in range(n)]

    #
    # constraints
    #
    circuit(model, x)

    #
    # solution and search
    #
    solver = cp.CpSolver()
    solver.parameters.search_branching = cp.PORTFOLIO_SEARCH
    solver.parameters.cp_model_presolve = False
    solver.parameters.linearization_level = 0
    solver.parameters.cp_model_probing_level = 0

    # status = solver.Solve(model)
    solution_printer = ListPrinter(x)
    _status = solver.SearchForAllSolutions(model, solution_printer)

    # if status == cp.OPTIMAL:
    #  print("x:", [solver.Value(x[i]) for i in range(len(x))])

    print()
    print("NumSolutions:", solution_printer.SolutionCount())
    print("NumConflicts:", solver.NumConflicts())
    print("NumBanches:", solver.NumBranches())
    print("WallTime:", solver.WallTime())
    print()
def main(base=10):

    model = cp.CpModel()

    # data

    # declare variables
    x = [model.NewIntVar(0, base - 1, f"x[{i}") for i in range(8)]
    s, e, n, d, m, o, r, y = x
    xx = [s, e, n, d, m, o, r, e, m, o, n, e, y]
    coeffs = [
        1000,
        100,
        10,
        1,  # S E N D +
        1000,
        100,
        10,
        1,  # M O R E
        -10000,
        -1000,
        -100,
        -10,
        -1  # == M O N E Y
    ]

    #
    # constraints
    #
    model.AddAllDifferent(x)
    model.Add(0 == cp.LinearExpr.ScalProd(xx, coeffs))
    model.Add(s > 0)
    model.Add(m > 0)

    #
    # solution and search
    #
    solver = cp.CpSolver()
    solution_printer = ListPrinter(x)
    status = solver.SearchForAllSolutions(model, solution_printer)

    if status != cp.OPTIMAL:
        print("No solution!")

    print()
    print("NumConflicts:", solver.NumConflicts())
    print("NumBranches:", solver.NumBranches())
    print("WallTime:", solver.WallTime())
    print()
Beispiel #13
0
def main(MONEY=0):

    model = cp.CpModel()

    # data

    # declare variables
    s = model.NewIntVar(0, 9, 's')
    e = model.NewIntVar(0, 9, 'e')
    n = model.NewIntVar(0, 9, 'n')
    d = model.NewIntVar(0, 9, 'd')
    m = model.NewIntVar(0, 9, 'm')
    o = model.NewIntVar(0, 9, 'o')
    t = model.NewIntVar(0, 9, 't')
    y = model.NewIntVar(0, 9, 'y')
    money = model.NewIntVar(0, 100000, 'money')

    x = [s, e, n, d, m, o, t, y]

    #
    # constraints
    #
    if MONEY > 0:
        model.Add(money == MONEY)

    model.AddAllDifferent(x)
    model.Add(money == m * 10000 + o * 1000 + n * 100 + e * 10 + y)
    model.Add(money > 0)
    model.Add(1000 * s + 100 * e + 10 * n + d + 1000 * m + 100 * o + 10 * s +
              t == money)
    model.Add(s > 0)
    model.Add(m > 0)

    if MONEY == 0:
        model.Maximize(money)

    #
    # solution and search
    #
    solver = cp.CpSolver()

    if MONEY == 0:
        status = solver.Solve(model)
    else:
        solution_printer = ListPrinter(x)
        status = solver.SearchForAllSolutions(model, solution_printer)

    money_val = 0
    if MONEY == 0 and status == cp.OPTIMAL:
        money_val = solver.Value(money)
        print("Optimal value of money:", money_val)
    else:
        print()
        print('NumSolutions:', solution_printer.SolutionCount())

    print('NumConflicts:', solver.NumConflicts())
    print('NumBranches:', solver.NumBranches())
    print('WallTime:', solver.WallTime())

    if MONEY == 0:
        return money_val
Beispiel #14
0
def main(opt=0):

    model = cp.CpModel()

    #
    # data
    #
    persons = ["Betty", "Chris", "Donald", "Fred", "Gary", "Mary", "Paul"]
    n = len(persons)
    preferences = [
        # 0 1  2  3  4  5  6
        # B C  D  F  G  M  P
        [0, 0, 0, 0, 1, 1, 0],  # Betty  0
        [1, 0, 0, 0, 1, 0, 0],  # Chris  1
        [0, 0, 0, 0, 0, 0, 0],  # Donald 2
        [0, 0, 1, 0, 0, 1, 0],  # Fred   3
        [0, 0, 0, 0, 0, 0, 0],  # Gary   4
        [0, 0, 0, 0, 0, 0, 0],  # Mary   5
        [0, 0, 1, 1, 0, 0, 0]  # Paul   6
    ]

    if opt == 0:
        print("""Preferences:
      1. Betty wants to stand next to Gary and Mary.
      2. Chris wants to stand next to Betty and Gary.
      3. Fred wants to stand next to Mary and Donald.
      4. Paul wants to stand next to Fred and Donald.
      """)

    #
    # declare variables
    #
    positions = [
        model.NewIntVar(0, n - 1, "positions[%i]" % i) for i in range(n)
    ]

    # successful preferences
    # z = model.NewIntVar(0, n * n, "z")
    z = model.NewIntVar(0, sum(flatten(preferences)), "z")

    #
    # constraints
    #
    model.AddAllDifferent(positions)

    # calculate all the successful preferences

    # b = [model.NewBoolVar("") for i in range(n) for j in range(n)]
    bb = []
    for i in range(n):
        for j in range(n):
            if preferences[i][j] == 1:
                b = model.NewBoolVar("b")
                p = model.NewIntVar(-n, n, "p")
                model.Add(p == positions[i] - positions[j])
                d = model.NewIntVar(-n, n, "d")
                # This don't work:
                # model.AddAbsEquality(d,p).OnlyEnforce(b)
                model.AddAbsEquality(d, p)
                model.Add(d == 1).OnlyEnforceIf(b)

                bb.append(b)

    model.Add(z == sum(bb))

    #
    # Symmetry breaking (from the Oz page):
    #   Fred is somewhere left of Betty
    model.Add(positions[3] < positions[0])

    # objective
    if opt == 0:
        model.Maximize(z)
    else:
        model.Add(z == opt)

    #
    # search and result
    #
    solver = cp.CpSolver()
    if opt == 0:
        status = solver.Solve(model)
    else:
        solution_printer = ListPrinter(positions)
        status = solver.SearchForAllSolutions(model, solution_printer)

    print("status:", solver.StatusName(status))
    if opt == 0 and (status == cp.OPTIMAL or status == cp.FEASIBLE):
        print("z:", solver.Value(z))
        p = [solver.Value(positions[i]) for i in range(n)]
        print("p:", p)

        print(" ".join(
            [persons[j] for i in range(n) for j in range(n) if p[j] == i]))
        print("Successful preferences:")
        for i in range(n):
            for j in range(n):
                if preferences[i][j] == 1 and abs(p[i] - p[j]) == 1:
                    print("\t", persons[i], persons[j])
        print()

        print("NumConflicts:", solver.NumConflicts())
        print("NumBranches:", solver.NumBranches())
        print("WallTime:", solver.WallTime())
        print()

    return solver.Value(z)