def solve(self): # Check if solvable if len(self.letters) > 10: print("Unsolvable, too many letters.") return 0 # Setup variables dictionary, -1 for unassigned letters AC3_Crypt.setupAC3(self.cons, self.vars) keys = list(self.vars.keys()) #keys = sorted(self.vars.keys(), key = lambda x: len(self.vars[x].domain)) for k in keys: print(k, len(self.vars[k].domain)) return self.backtrace(self.cons, self.vars, keys, 0)
def backtrace(self, constraints, variables, keys, keyIndex, currentVar=None): self.nodesExplored += 1 # Check if solution is found, or there is no solution varCopy = copy.deepcopy(variables) state = AC3_Crypt.AC3(constraints, varCopy, currentVar) if state == -1: return None if state == 1: if self.testSumSolution(varCopy): return varCopy else: return None keyVal = keys[keyIndex] #print(keyVal) domain = copy.deepcopy(varCopy[keyVal].domain) # Try each possible value for the variable for d in list(domain): varCopy[keyVal].domain = [d] # Guesses next variable state = self.backtrace(constraints, varCopy, keys, keyIndex + 1, varCopy[keyVal]) if state != None: return state return None
def solve(self): # Check if solvable if len(self.letters) > 10: print("Unsolvable, too many letters.") return 0 t = time.time() # Setup the variables and constraints, runs AC3 once. AC3_Crypt.setupAC3(self.cons, self.vars) keys = list(self.vars.keys()) #keys = sorted(self.vars.keys(), key = lambda x: len(self.vars[x].domain)) #for k in keys: #print(k, len(self.vars[k].domain)) final = self.backtrace(self.cons, self.vars, keys, 0) t = time.time() - t print("MAC Time Taken: ", t) print("MAC Nodes Explored: ", self.nodesExplored) return final
def backtrace(self, constraints, variables, keys, keyIndex, currentVar=None): varCopy = copy.deepcopy(variables) state = AC3_Crypt.AC3(constraints, varCopy, currentVar) if state == -1: return None if state == 1: if self.testSumSolution(varCopy): return varCopy else: return None # Perform MRV Here. the most restricted is chosen first # Reorder all keys at every level to give the most restrictive one to the front. keys = self.MRVOrder(variables, keys, currentVar) if keyIndex >= len(keys): keyIndex = 0 keyVal = keys[keyIndex] #print(keyVal) domain = copy.deepcopy(varCopy[keyVal].domain) for d in list(domain): varCopy[keyVal].domain = [d] state = self.backtrace(constraints, varCopy, keys, keyIndex + 1, varCopy[keyVal]) if state != None: return state return None
def setupCSP( self ): ''' This function is used to set up variables and their initial domain. ''' return AC3_Crypt.setupProblem()
def runAC3(): const = [] vars = dict() AC3_Crypt.setupAC3(const, vars) AC3_Crypt.AC3(const, vars, None)
def setupCSP(self): ''' This function is used to set up variables and their initial domain. ''' return AC3_Crypt.setupProblem()