def round_seq_preserving_sum(seq: Seq[float], minval=1, maxval:int=None) -> Opt[List[int]]: """ Round the elements of seq preserving the sum so that sum(seq_rounded) == sum(seq) given: sum(seq) will be rounded """ seqsum = round(sum(seq)) if maxval is None: maxval = int(min(max(seq) + 1, seqsum)) p = constraint.Problem() numvars = len(seq) variables = list(range(numvars)) domain = list(range(minval, maxval+1)) p.addVariables(variables, domain) for var, optimalval in zip(variables, seq): func = lambda intval, floatval: abs(intval - floatval) <= 1 p.addConstraint(partial(func, optimalval), [var]) p.addConstraint(constraint.ExactSumConstraint(seqsum), variables) solutions = p.getSolutions() if not solutions: return None solutions.sort(key=lambda sol: sum(abs(v-x) for v, x in zip(list(sol.values()), seq))) solution = list(solutions[0].items()) solution.sort() varnames, values = list(zip(*solution)) return values
def solve(self): """ Solves the sudoku. This will replace the empty cells in this sudoku with the solutions. """ problem = constraint.Problem() all_different = constraint.AllDifferentConstraint() for i, n in enumerate(self.grid): problem.addVariable(i, range(1, self.size + 1) if n == 0 else [n]) _s = Sudoku(range(len(self.grid))) for row in _s.rows: problem.addConstraint(all_different, row) for col in _s.columns: problem.addConstraint(all_different, col) for block in _s.blocks: problem.addConstraint(all_different, block) solution = problem.getSolution() if solution: self.grid = solution.values() else: raise ValueError('No solutions found')
def findmatch(self): solutions = [] for i in range(len(self.date)): temp = [] var = [] for man in self.workers: if man.day.__contains__(i + 1): rank = [j for j in man.regions] var += [(str(man._index) + "," + str(i + 1), rank)] # getting permutation of worker. # for example for 10 worker and 6 regions we will check all combination of 6 from 10. comb = combinations(var, len(self.regions)) for p in comb: problem = constraint.Problem() for permutation in p: problem.addVariable(permutation[0], permutation[1]) problem.addConstraint(constraint.AllDifferentConstraint()) temp += problem.getSolutions() if len(temp) == 0: return None solutions += [temp] if len(solutions) == 0: return None return self._find_opt(solutions)
def solve(self, numslots): values = self.values dur = self.dur timeout = self.timeout problem = constraint.Problem() slots = list(range(numslots)) problem.addVariables(slots, values) if dur is not None: if self.relError is None and self.absError is None: absError = min(values) elif self.absError is None: absError = self.relError * dur elif self.relError is None: absError = self.absError else: absError = min(self.absError, self.relError * dur) problem.addConstraint(constraint.MinSumConstraint(dur - absError)) problem.addConstraint(constraint.MaxSumConstraint(dur + absError)) if self.fixedslots: for idx, slotdur in self.fixedslots.items(): try: slot = slots[idx] problem.addConstraint( lambda s, slotdur=slotdur: s == slotdur, variables=[slot]) except IndexError: pass self._applyConstraints(problem, slots) for callback in self._constraintCallbacks: callback(problem, slots) return getSolutions(problem, numSlots=numslots, timeout=timeout)
def constraint_solver(puzzle: NumberMindPuzzle): """ Solves a number-mind puzzle using Gustavo Niemeyer's python constraint module. This isn't suitable for solving the length 16 number-mind puzzle, but it can solve the length 5 puzzle. """ def make_constraint_function(guess, score): """ Helper function for the constraint solver. Returns a function that gives a score for a guess vs a proposed solution. """ def cf(*args): num_corr = sum(guess[j] == args[j] for j in range(len(guess))) return num_corr == score return cf problem = constraint.Problem(constraint.RecursiveBacktrackingSolver()) v_list = ['v' + str(a) for a in range(puzzle.length)] for v in v_list: problem.addVariable(v, list('01234567890')) for i in range(puzzle.num_guesses): problem.addConstraint( make_constraint_function(puzzle.guesses[i], puzzle.scores[i]), v_list) sol = problem.getSolution() if sol: sol_str = ''.join(sol[v] for v in v_list) print( "{} Generalized constraint solver found solution.".format(sol_str)) return print( "Generalized constraint solver determined that puzzle has no solution." )
def solve(assign_list_str, end_cond, affected_vars): print "solving" problem = constraint.Problem() print affected_vars for var in affected_vars: problem.addVariable(var, range(1000)) for a in assign_list_str: print a f_body = assign_list_str f_body.append("return %s and \\" % ast2str.cond(end_cond[0])) for cond in end_cond[1:]: c_s = ast2str.cond(cond) print c_s f_body.append("True") print "here" print f_body print "done" av_list = list(affected_vars) argsstr = ', '.join([a for a in av_list]) print argsstr, av_list cons_f = str2py.function(argsstr, assign_list_str) problem.addConstraint(cons_f, av_list) print cons_f(0, 1) print problem.getSolution()
def single_1d_gray_code(n=DEFAULT_N, m=None, do_print=True, looping=True): """return a single length-n code of m-bit binary numbers such that each adjacent numbers in the code share all but one bit in their binary representations, i.e. are valid Gray code transitions""" if m is None: m = n all_keys = get_unique_variables(n) format_flag = '0%ib' % m problem = constraint.Problem() problem.addVariables(all_keys[:2**n], range(2**m)) problem.addConstraint(constraint.AllDifferentConstraint()) for i in range(2**n - 1): problem.addConstraint(lambda a, b: valid_neighbors(a, b, format_flag), (all_keys[i], all_keys[i + 1])) problem.addConstraint(lambda a: a == 0, (all_keys[0])) if looping: # only one bit switch from last to first code value problem.addConstraint(lambda a, b: valid_neighbors(a, b, format_flag), (all_keys[0], all_keys[2**n - 1])) else: # go from start to end of range, e.g., 000 --- 111 problem.addConstraint(lambda a: a == 2**n - 1, (all_keys[2**n - 1])) soln = problem.getSolution() if do_print: print('soln') for i, key in enumerate(soln.keys()): print('%i | %s' % (i, format(soln[all_keys[i]], format_flag))) return numeric_soln(soln, all_keys)
def solve(S): problem = constraint.Problem() #name the circles as A,B,C,D,E,F FROM 1-6 problem.addVariable(("A"), range(1, 7)) problem.addVariable(("B"), range(1, 7)) problem.addVariable(("C"), range(1, 7)) problem.addVariable(("D"), range(1, 7)) problem.addVariable(("E"), range(1, 7)) problem.addVariable(("F"), range(1, 7)) #this method is used for sum of each side so that each side has same sum def sum1(a, b, c, d, e, f): if (a + b + c == c + d + e == S and c + d + e == e + f + a == S and a + b + c == e + f + a == S): return True problem.addConstraint(sum1, "ABCDEF") problem.addConstraint( constraint.AllDifferentConstraint()) #each circle got distinct number solutions = problem.getSolutions() #get solution return solutions
def kit_combinations(): hit_combos = SETTINGS.data["multiclassed"]["hit_combinations"] breakdown = hit_breakdown() kit_combos = [] # For each hit combination do constraint programming to find all combinations of kit_label - tech_label hits for hc in hit_combos: prob = c.Problem() var_i = 0 for ht in hc: prob.addVariable(str(var_i), breakdown[ht]) var_i += 1 # Kit type contraint (they must be unique) prob.addConstraint(unique_kit_class) # Remove permutations of hits kit_combo_subset = list( reduce( lambda acc, x: [*acc, set(x.values())] if set(x.values()) not in acc else acc, prob.getSolutions(), [])) # Check elements of subset aren't already in kit_combos list kit_combo_subset = list( filter(lambda x: x not in kit_combos, kit_combo_subset)) # Add to kit_combos kit_combos.extend(kit_combo_subset) kit_combos.sort(key=set_to_hash) return kit_combos
def ai_player_csp(state, board): csp = constraint.Problem() rows, cols = len(state[0]), len(state[0][0]) fringe_cells = set() for i, j in np.ndindex((rows, cols)): if state[0][i][j].isdigit(): n = int(state[0][i][j]) neighbors = [(x, y) for x, y in surrounding_cells(i, j, rows, cols) if state[0][x][y] == '#'] fringe_cells.update(neighbors) csp.addConstraint(constraint.ExactSumConstraint(n), neighbors) csp.addVariables(fringe_cells, [0, 1]) solutions = csp.getSolutions() print(len(solutions)) if solutions: fringe_dict = defaultdict(float) for solution in solutions: for cell in solution.keys(): fringe_dict[cell] += solution[cell] safe = min(fringe_dict, key=fringe_dict.get) mine = max(fringe_dict, key=fringe_dict.get) if fringe_dict[safe] != fringe_dict[mine]: return safe return ai_player(state, board)
def solve(self): """Fills out self.values using python-constraint's CSP solver.""" #problem = C.Problem(C.MinConflictsSolver(100000)) #problem = C.Problem(C.BacktrackingSolver()) #problem = C.Problem(C.RecursiveBacktrackingSolver()) problem = C.Problem() # Add variables for y in range(self.rows): for x in range(self.cols): if (x, y) in self.given_values: problem.addVariable((x, y), [self.given_values[x, y]]) else: problem.addVariable((x, y), range(1, len(self.segment_of((x, y))) + 1)) # Add constraints: each segment must have all values different for segment in self.segments: for pos1 in segment: for pos2 in segment: if pos1 < pos2: problem.addConstraint(lambda p1, p2: p1 != p2, (pos1, pos2)) # Add look-around constraints for y in range(self.rows): for x in range(self.cols): self.add_look_constraints((x, y), problem) # Solve the CSP solution = problem.getSolution() assert solution is not None #print(problem.getSolutions()) self.solved_values = solution
def make_problem(blocks=9, block_size=3, possible_values=range(1, 10)): indices = list( range(i * blocks, i * blocks + blocks) for i in xrange(blocks)) problem = constraint.Problem() def ensure_unique_values(varnames): # we don't want variable names to interfere with values, # so we convert them to strings problem.addConstraint(constraint.AllDifferentConstraint(), map(str, varnames)) for vars in indices: problem.addVariables(map(str, vars), possible_values) # ensure all values are unique per row ensure_unique_values(vars) for vars in zip(*indices): # ensure all values are unique per column ensure_unique_values(vars) def block_indices(n): (x, y) = divmod(n, block_size) x *= block_size y *= block_size g_indices = list() for i in xrange(block_size): g_indices.extend(indices[x + i][y:y + block_size]) return g_indices for i in xrange(blocks): # ensure all values are unique per block ensure_unique_values(block_indices(i)) return problem
def buildProblem(N): problem = constraint.Problem() problem.addVariables(range(1, N + 1), range(1, N + 1)) problem.addConstraint(constraint.AllDifferentConstraint()) addDiagonalConstraints(problem, xrange(1, N + 1)) return problem
def p2(): valid_tickets = [ list(map(int, x.split(','))) for x in near_tx[1:] if is_valid(x)[0] ] field_names = list(validators.keys()) W = len(field_names) p = constraint.Problem() p.addVariables(["col_" + str(i) for i in range(W)], range(W)) p.addConstraint(constraint.AllDifferentConstraint()) for col in range(W): p.addConstraint(AllValidConstraint(valid_tickets, col), ["col_" + str(col)]) soln = p.getSolution() def sorter(kv): return int(kv[0].split('_')[1]) your_t = 1 your_ticket = map(int, your_tx[1].split(',')) for val, (col, field) in zip(your_ticket, sorted(soln.items(), key=sorter)): if field_names[field].startswith('departure'): # print(f'({col})', field_names[field], '=', val) your_t *= val print(your_t) return your_t
def graphColoringExample(): # First step is to initialize a Problem() from the 'constraint' package. colorProblem = constraint.Problem() # Next, we will define the values the variables can have, and add them to our problem. domains = ["red", "green", "blue"] colorProblem.addVariable("WA", domains) # Ex: "WA" can be "red", "green", or "blue" colorProblem.addVariable("NT", domains) colorProblem.addVariable("Q", domains) colorProblem.addVariable("NSW", domains) colorProblem.addVariable("V", domains) colorProblem.addVariable("SA", domains) colorProblem.addVariable("T", domains) # We then add in all of the constraints that must be satisfied. # In the map coloring problem we are doing, this means that each section # cannot be the same color as any of its neighbors. # There are other types of constraints you can add if you want to look at the documentation. # However, this type will suffice to do the assignment. colorProblem.addConstraint(lambda a, b: a != b, ("WA", "NT")) # Ex: WA can't be same value (color) as NT colorProblem.addConstraint(lambda a, b: a != b, ("WA", "SA")) colorProblem.addConstraint(lambda a, b: a != b, ("SA", "NT")) colorProblem.addConstraint(lambda a, b: a != b, ("Q", "NT")) colorProblem.addConstraint(lambda a, b: a != b, ("SA", "Q")) colorProblem.addConstraint(lambda a, b: a != b, ("NSW", "SA")) colorProblem.addConstraint(lambda a, b: a != b, ("NSW", "Q")) colorProblem.addConstraint(lambda a, b: a != b, ("SA", "V")) colorProblem.addConstraint(lambda a, b: a != b, ("NSW", "V")) # The constraint problem is now fully defined and we let the solver take over. # We call getSolution() and print it. print colorProblem.getSolution()
def constraint_based_generation( preconditions, attributes, actions, causal_relation_types, perceptually_causal_relations, ): # manually generator the causal relations with parents so that the precondition matches the fluent precondition state precondition_match_csp = constraint.Problem() precondition_match_csp.addVariable("preconditions", preconditions) precondition_match_csp.addVariable("attributes", attributes) precondition_match_csp.addVariable("actions", actions) precondition_match_csp.addVariable("fluents", causal_relation_types) # add in constraint that precondition state must match fluent's precondition precondition_match_csp.addConstraint( lambda precondition, fluent: precondition is None or precondition[ 1] == fluent.value[0], ("preconditions", "fluents"), ) # add constraints for perceptually causal relations for perceptually_causal_relation in perceptually_causal_relations: # causal relation (fluent change) precondition_match_csp.addConstraint( lambda attributes, action, fluent: fluent == perceptually_causal_relation.causal_relation_type if (attributes == perceptually_causal_relation.attributes and action == perceptually_causal_relation.action) else True, # if the attributes and action do not match, always accept ("attributes", "actions", "fluents"), ) causal_relations = precondition_match_csp.getSolutions() return causal_relations
def __init__(self, name=""): self.name = name self.instr_group = "Instruction Group" self.instr_format = "Instruction Format" self.instr_category = "Instruction Category" self.instr_name = "Instruction Name" self.instr_imm_t = "Instruction Immediate Type" self.instr_src2 = "Instruction Source 2" self.instr_src1 = "Instruction Source 1" self.instr_rd = "Instruction Destination" self.imm = "Instruction Immediate" self.imm_length = "Instruction Immediate Length" self.imm_str = "" self.csr = "CSR" self.comment = "" self.has_label = 1 self.label = "" self.idx = -1 self.atomic = 0 # As of now, we don't support atomic instructions. self.is_compressed = 0 # As of now, compressed instructions are not supported self.is_illegal_instr = 0 self.is_local_numeric_label = 0 self.is_pseudo_instr = "Is it a pseudo instruction or not" self.branch_assigned = 0 self.process_load_store = 1 self.solution = "A random solution which meets given constraints" self.problem = constraint.Problem(constraint.MinConflictsSolver())
def create_csp_problem(self, solver=constraint.BacktrackingSolver(), symmetry_break=False): p = constraint.Problem(solver) p.addVariables(self.nodes(), self.colors()) self.add_edge_constraint(p) return p
def equality_problem(): problem = constraint.Problem() problem.addVariables(['alfa', 'beta'], [1, 2, 3, 4]) problem.addVariables('ij', [1, 3]) problem.addConstraint(lambda a, b, i, j: a + b == i + j, ['alfa', 'beta', 'i', 'j']) solutions = problem.getSolutions() return solutions
def solve_grid(grid, unknownVariableSymbol=0): """ Function to solve a sudoku grid with constraint logic programming. Only supports classic sudoku grids. :param grid: (np.array(9,9)) the sudoku grid to be solved. :param unknownVariableSymbol: (str, or 0) the symbol that was used to indicate an unknown value in the sudoku grid. :return: a numpy array of shape (9,9), i.e. the solved sudoku grid. """ # Sanity checks assert type( grid ) == np.ndarray, '\'grid\' should be a numpy.ndarray of shape (9,9)' assert grid.shape == ( 9, 9), '\'grid\' should be a numpy.ndarray of shape (9,9)' if type(unknownVariableSymbol) == int: assert not 1 <= unknownVariableSymbol <= 9, '\'unknownVariableSymbol\' should not be between 1 and 9' if unknownVariableSymbol != 0: grid[grid == unknownVariableSymbol] = 0 grid = grid.astype(int) sudoku = clp.Problem() # Introducing 81 variables. Each variable is represented by a number between [1; 81] and # can take a value between [1; 9]. variablesGrid = np.arange(1, 82).reshape((9, 9)) possibleValues = np.arange(1, 10, dtype=int) sudoku.addVariables(variablesGrid.flatten(), possibleValues.tolist()) # Fix values for known variables knownVariables = np.nonzero(grid) for i, j in zip(knownVariables[0], knownVariables[1]): sudoku._variables.pop(variablesGrid[i][j]) sudoku.addVariable(variablesGrid[i][j], [grid[i][j]]) # Adding constraints for each row for row in variablesGrid: sudoku.addConstraint(clp.AllDifferentConstraint(), row.tolist()) # Adding constraints for each column for col in variablesGrid.T: sudoku.addConstraint(clp.AllDifferentConstraint(), col.tolist()) # Adding constraints for each sub-grid for i in range(0, 7, 3): for j in range(0, 7, 3): sudoku.addConstraint( clp.AllDifferentConstraint(), variablesGrid[i:i + 3, j:j + 3].flatten().tolist()) # The solution is returned as a dictionary where each (key, value) pair is a (Variable, Value) pair solutionDic = sudoku.getSolution() solution = [solutionDic[key] for key in variablesGrid.flatten()] return np.reshape(solution, (9, 9))
def constraint_checker(piece_1, piece_2, piece_3, piece_4, piece_5, piece_6, piece_7, piece_8, piece_9, timing=False): # Find the start time if we want the execution time for this function if timing: start_time = time.time() # Create the set of rotations for each piece piece_1_set = [list(np.roll(piece_1, i)) for i in range(4)] piece_2_set = [list(np.roll(piece_2, i)) for i in range(4)] piece_3_set = [list(np.roll(piece_3, i)) for i in range(4)] piece_4_set = [list(np.roll(piece_4, i)) for i in range(4)] piece_5_set = [list(np.roll(piece_5, i)) for i in range(4)] piece_6_set = [list(np.roll(piece_6, i)) for i in range(4)] piece_7_set = [list(np.roll(piece_7, i)) for i in range(4)] piece_8_set = [list(np.roll(piece_8, i)) for i in range(4)] piece_9_set = [list(np.roll(piece_9, i)) for i in range(4)] # Initialise the constraint problem class problem = constraint.Problem() # Add the variables to the problem and their domain sets problem.addVariable("1", piece_1_set) problem.addVariable("2", piece_2_set) problem.addVariable("3", piece_3_set) problem.addVariable("4", piece_4_set) problem.addVariable("5", piece_5_set) problem.addVariable("6", piece_6_set) problem.addVariable("7", piece_7_set) problem.addVariable("8", piece_8_set) problem.addVariable("9", piece_9_set) # Add the constraints required to solve the puzzle problem.addConstraint(lambda i, j: i[1] + j[3] == 0, ("1", "2")) problem.addConstraint(lambda i, j: i[1] + j[3] == 0, ("4", "5")) problem.addConstraint(lambda i, j: i[1] + j[3] == 0, ("7", "8")) problem.addConstraint(lambda i, j: i[1] + j[3] == 0, ("2", "3")) problem.addConstraint(lambda i, j: i[1] + j[3] == 0, ("5", "6")) problem.addConstraint(lambda i, j: i[1] + j[3] == 0, ("8", "9")) problem.addConstraint(lambda i, j: i[2] + j[0] == 0, ("1", "4")) problem.addConstraint(lambda i, j: i[2] + j[0] == 0, ("4", "7")) problem.addConstraint(lambda i, j: i[2] + j[0] == 0, ("2", "5")) problem.addConstraint(lambda i, j: i[2] + j[0] == 0, ("5", "8")) problem.addConstraint(lambda i, j: i[2] + j[0] == 0, ("3", "6")) problem.addConstraint(lambda i, j: i[2] + j[0] == 0, ("6", "9")) # Give a list of all solutions solutions = problem.getSolutions() # Find end time and difference, return this with solutions if timing: end_time = time.time() execution_time = end_time - start_time return solutions, execution_time else: return solutions
def p(n): p = constraint.Problem() p.addVariables(range(n), N) p.addConstraint(constraint.AllDifferentConstraint()) p.addConstraint(constraint.ExactSumConstraint(2020)) try: print(prod(p.getSolution().values())) except: print("")
def __init__(self, name): self.name = name self.program_id = "ID of the current program" self.call_stack_level = ( "The level of current program in the call stack " "tree") self.sub_program_id = [ ] # The list of all sub-programs of the current program self.solution = "A random solution which meets given constraints" self.problem = constraint.Problem(constraint.MinConflictsSolver())
def part1_csp(unused): import constraint problem = constraint.Problem() problem.addVariable("password", range(RANGE_LO, RANGE_HI + 1)) # KF2 problem.addConstraint(has_increasing, ("password",)) # KF4 problem.addConstraint(has_same_adjacent, ("password",)) # KF3 problem.addConstraint(lambda p: len(str(p)) == 6, ("password",)) # KF1 sols = problem.getSolutions() return len(sols)
def post_randomize(self): last_level = self.stack_level[self.program_cnt - 1] for i in range(len(self.program_h)): self.program_h[i].program_id = i self.program_h[i].call_stack_level = self.stack_level[i] # Top-down generate the entire call stack. # A program can only call the programs in the next level. for i in range(last_level): program_list = [] next_program_list = [] idx = 0 # sub_program_id_pool = [] # sub_program_cnt = [] for j in range(len(self.stack_level)): if self.stack_level[j] == i: program_list.append(j) if self.stack_level[j] == i + 1: next_program_list.append(j) # Randomly duplicate some sub programs in the pool to create a case that # one sub program is called by multiple caller. Also it's possible to call # the same sub program in one program multiple times. total_sub_program_cnt = random.randint(len(next_program_list), len(next_program_list) + 1) sub_program_id_pool = [None] * total_sub_program_cnt for j in range(len(sub_program_id_pool)): if j < len(next_program_list): sub_program_id_pool[j] = next_program_list[j] else: sub_program_id_pool[j] = random.choice(next_program_list) random.shuffle(sub_program_id_pool) sub_program_cnt = [None] * len(program_list) for i in range(len(program_list)): sub_program_cnt[i] = i # Distribute the programs of the next level among the programs of current level # Make sure all program has a caller so that no program is obsolete. problem = constraint.Problem(constraint.MinConflictsSolver()) problem.addVariables(sub_program_cnt, range(0, len(sub_program_id_pool) + 1)) problem.addConstraint( constraint.ExactSumConstraint(len(sub_program_id_pool)), [item for item in sub_program_cnt]) solution = problem.getSolution() for j in range(len(program_list)): id = program_list[j] self.program_h[id].sub_program_id = [ None ] * solution[sub_program_cnt[j]] for i in range(len(self.program_h[id].sub_program_id)): self.program_h[id].sub_program_id[i] = sub_program_id_pool[ idx] idx += 1
def __createBasicCSP(self): self.__cspVariablesStrings = [] cspProblem = constraint.Problem() cspVariablesIntervals = list(range(self.__numberOfColors)) for count in range(self.__lengthOfGuess): newVariable = "c_" + str(count) self.__cspVariablesStrings.append(newVariable) cspProblem.addVariable(newVariable, cspVariablesIntervals) cspProblem.addConstraint(constraint.AllDifferentConstraint()) cspProblem.setSolver(self.cspSolvingStrategy) return cspProblem
def empty_puzzle_as_CP(boxsize, solver=constraint.BacktrackingSolver()): """empty_puzzle(boxsize) -> constraint.Problem Returns a constraint problem representing an empty Sudoku puzzle of box-dimension 'boxsize'.""" p = constraint.Problem(solver) p.addVariables(cells(boxsize), symbols(boxsize)) add_row_constraints(p, boxsize) add_col_constraints(p, boxsize) add_box_constraints(p, boxsize) return p
def create_add_problem(addend, summ): if type(addend) is not list or type(addend[0]) is not str: raise TypeError('addend must be a list of strings') problem = constraint.Problem() variables = _get_variable_list(addend, summ) problem = _add_vars_to_problem(problem, variables) problem.addConstraint(constraint.AllDifferentConstraint()) problem = _generate_constraints(problem, addend, summ) return problem
def create_problem(min_value: int, max_value: int) -> constraint.Problem: """ Creates a simple problem that, with a large enough input domain, should run for a while and waste some CPU cycles. """ problem = constraint.Problem() problem.addVariable("a", range(min_value, max_value)) problem.addVariable("b", range(min_value, max_value)) problem.addConstraint(lambda a, b: a == b * 10, ("a", "b")) return problem
def sudokuCSP(positions, psize): sudokuPro = constraint.Problem() dim = psize ** 2 numCol = dim numRow = dim domains = range(1, dim + 1) init = {str(dim * p[0] + p[1] + 1): p[2] for p in positions} sudokuList = [str(i) for i in range(1, dim ** 2 + 1)] sudoKuGrid = np.reshape(sudokuList, [numRow, numCol]) addVar(sudokuPro, sudoKuGrid, domains, init) cstAdd(sudokuPro, sudoKuGrid, domains, psize) return sudokuPro.getSolution()