diff --git a/assignment2/csp.py b/assignment2/csp.py index 1d17bc6..53fe7d1 100644 --- a/assignment2/csp.py +++ b/assignment2/csp.py @@ -56,8 +56,47 @@ class CSP: bool False if a domain becomes empty, otherwise True """ - # YOUR CODE HERE (and remove the assertion below) - assert False, "Not implemented" + queue = Queue() + for edge in self.binary_constraints.keys(): + queue.put(edge) + + while not queue.empty(): + (xi, xj) = queue.get() + + if self._revise(xi, xj): + if len(self.domains[xi]) == 0: + return False + for neighboring_edge in [ + (a, b) + for (a, b) in self.binary_constraints.keys() + if a != xj and b == xi + ]: + queue.put(neighboring_edge) + return True + + def _revise(self, xi, xj) -> bool: + """Internal of ac_3 + Makes an arc consistent by shrinking xi's domain. + + Parameters + ---------- + xi, xj + Nodes of the arc + + Returns + ------- + bool + True if a change was made to the domain of xi, False otherwise + + """ + revised = False + for x in set(self.domains[xi]): + if not any( + [(x, y) in self.binary_constraints[(xi, xj)] for y in self.domains[xj]] + ): + self.domains[xi].remove(x) + revised = True + return revised def _consistent(self, var, value, assignment) -> bool: for v in assignment: