Exemplo n.º 1
0
    def __init__(self, colors, neighbors):
        """Make a CSP for the problem of coloring a map with different colors
        for any two adjacent regions. Arguments are a list of colors, and a
        dict of {region: [neighbor,...]} entries. This dict may also be
        specified as a string of the form defined by parse_neighbors."""

        def parse_neighbors(neighbors):
            """Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping
            regions to neighbors. The syntax is a region name followed by a ':'
            followed by zero or more region names, followed by ';', repeated for
            each region name. If you say 'X: Y' you don't need 'Y: X'.
            """
            dic = defaultdict(list)
            specs = [spec.split(':') for spec in neighbors.split(';')]
            for (A, Aneighbors) in specs:
                A = A.strip()
                for B in Aneighbors.split():
                    dic[A].append(B)
                    dic[B].append(A)
            return dic

        if isinstance(neighbors, str):
            neighbors = parse_neighbors(neighbors)

        def different_values_constraint(A, a, B, b):
            """A constraint saying two neighboring variables must differ in value."""
            return a != b
        CSP.__init__(self, list(neighbors.keys()), UniversalDict(
            colors), neighbors, different_values_constraint)
Exemplo n.º 2
0
    def __init__(self, grid):
        domains = {}
        for var in flatten(self.bgrid):
            domains[var] = ['V', 'R', 'A', '.']

        CSP.__init__(self, None, domains, self.neighbors,
                     self.pic_a_pix_constraint)
 def __init__(self, n):
     """Initialize data structures for n Queens."""
     CSP.__init__(self, range(n), UniversalDict(range(n)),
                  UniversalDict(range(n)), queen_constraint)
     update(self,
            rows=[0] * n,
            ups=[0] * (2 * n - 1),
            downs=[0] * (2 * n - 1))
Exemplo n.º 4
0
 def __init__(self, n):
     """Initialize data structures for n Queens.
     As we are choosing only the y coordinate of every queen the 
     domain and the neighbors are list(range(n)) for every column
     (alias variable)
     """
     CSP.__init__(self, list(range(n)), UniversalDict(list(range(n))),
                  UniversalDict(list(range(n))), queen_constraint)
Exemplo n.º 5
0
 def __init__(self, filename):
     """Create a Kenken puzzle by taking all the neccessary input from the specified text file"""
     ln = 0  # number of line-to-read
     with open(filename) as f:  # take input from the text file
         for line in f:
             ln += 1  # the line that we are reading
             if ln == 1:
                 print(line)
                 self.n = int(line)
             else:
                 a = line.split()
                 b = list()
                 pairs = ast.literal_eval(a[0])
                 for p in pairs:
                     b.append("K" + str(p[0]) + str(p[1]))
                 c = list()
                 c.append(b)
                 c.append(a[1])
                 c.append(ast.literal_eval(a[2]))
                 self.cage_constraints.append(c)
     # fill variables' list
     for i in range(0, self.n):
         for j in range(0, self.n):
             self.variables.append("K" + str(i) + str(j))
     # fill cages' dictionary
     for constr in self.cage_constraints:
         for c1 in constr[0]:
             self.cages[c1] = constr
     # fill variable domains' dictionary
     for v in self.variables:
         self.domains[v] = [i for i in range(1, self.n + 1)]
     # initialize lists for neighbors' dictionary members
     for v in self.variables:  # initialize neighbors
         self.neighbors[v] = list()
     # fill neighbors' dictionary
     for v1 in self.variables:
         for v2 in self.variables:  # neighbors by row or column constraint
             if (v1 != v2) and (
                 (v1[1] == v2[1]) or
                 (v1[2] == v2[2])) and (v2 not in self.neighbors[v1]):
                 self.neighbors[v1].append(v2)
     # print the structures that we have created so far
     print("Variables : ", self.variables)
     print("Domains : ", self.domains)
     print("Cage constraints : ", self.cage_constraints)
     #print("Cages : ", self.cages)
     #print("Neighbors : ", self.neighbors)
     print("")  # in order to change line
     # initialize CSP
     CSP.__init__(self, self.variables, self.domains, self.neighbors,
                  self.kenken_constraint)
Exemplo n.º 6
0
    def __init__(self, grid):
        """Build a Sudoku problem from a string representing the grid:
        the digits 1-9 denote a filled cell, '.' or '0' an empty one;
        other characters are ignored."""
        squares = iter(re.findall(r'\d|\.', grid))
        domains = {var: [ch] if ch in '123456789' else '123456789'
                   for var, ch in zip(flatten(self.rows), squares)}
        for _ in squares:
            raise ValueError("Not a Sudoku grid", grid)  # Too many squares

        def different_values_constraint(A, a, B, b):
            """A constraint saying two neighboring variables must differ in value."""
            return a != b
        CSP.__init__(self, None, domains, self.neighbors,
                     different_values_constraint)
Exemplo n.º 7
0
    def __init__(self,
                 columns=5,
                 rowConfigurations=None,
                 columnConfigurations=None):
        v = None
        self.board = [[0 for x in range(columns)] for y in range(columns)]
        self.rows = columns
        self.columns = columns
        self.columnConfigurations, self.rowConfigurations = self.setupConstraints(
            rowConfigurations, columnConfigurations)

        self.domain = ["Red", "Green", "Red", 0]
        self.variables = self.board

        # TODO
        CSP.__init__(self, self.variables, self.domain, None, None)
Exemplo n.º 8
0
    def __init__(self, grid):
        """
        Init method of Sudoku class. The parameter grid contains the definition of the sudoku board.
        This method is devoted to populate the __init_ method of CSP class, creating and passing
        variables, domains and neighbors from the grid parameter.
        """
        BLOCK_SIZE = 3
        BLOCKS_IN_ROW = 3
        ROW_SIZE = 9
        COL_SIZE = 9

        # Variables -
        # Variables definition. The varibles are an array with a sequence of indexes, from 0 to 80.

        self.variables = [x for x in range(ROW_SIZE * COL_SIZE)]
        # Domains -
        # Domains defintion. In this case of Sudoku CSP, the domains are '123456789' for empty cells and
        # the value of cell for cells with the default value.
        original_grid = list(iter(re.findall(r'\d|\.', grid)))
        domains = {}
        counter = 0
        for item in original_grid:
            if item == '.':
                domains[int(counter)] = '123456789'
            else:
                value = int(item)
                restricted_domain = [str(value)]
                domains[int(counter)] = restricted_domain
            counter += 1

        # Neighbors
        # Neighbors of binary-constraint definition. This dictionary contains the relations among a cell with its row,
        # column and block.
        neighbors = {}

        # rows
        # ∀ a
        # ∀ i ≠ j: xai ≠ xaj
        for a in range(ROW_SIZE):
            row_start = a * BLOCKS_IN_ROW * BLOCK_SIZE
            row_stop = a * BLOCKS_IN_ROW * BLOCK_SIZE + BLOCKS_IN_ROW * BLOCK_SIZE
            row_indexes = list(range(row_start, row_stop))
            for item in row_indexes:
                neighbors[int(item)] = list()
                item_neighbors = list(copy.copy(row_indexes))
                item_neighbors = [x for x in item_neighbors if x != item]
                neighbors[int(item)] += item_neighbors

        # columns
        # ∀ b
        # ∀ h ≠ k : xbh ≠ xbk
        for b in range(COL_SIZE):
            col_indexes = [ROW_SIZE * a + b for a in range(COL_SIZE)]
            for item in col_indexes:
                item_neighbors = list(copy.copy(col_indexes))
                item_neighbors = [x for x in item_neighbors if x != item]
                neighbors[int(item)] += item_neighbors

        # blocks
        # A block is a submatrix of sudoku grid:
        # a = {1, 4, 7}:  i, j = [a, a + 2]
        # b = {1, 4, 7}:  k, h = [b, b + 2]
        # {xpq} p = a...a + 2, q = b...b + 2 ∈ A ∈ N^(3x3)
        # where
        # ∀a:  i, j = [a, a + 2]
        # ∀b:  k, h = [b, b + 2]
        # ∀ h ≠ k or i ≠ j: xik ≠ xj, h
        a = b = [0, 3, 6]
        for b_row in a:
            for b_col in b:
                # block
                block_items = []
                for r in range(3):
                    for c in range(3):
                        block_items.append((b_row + r) * ROW_SIZE + b_col + c)

                for item in block_items:
                    item_neighbors = list(copy.copy(block_items))
                    item_neighbors = [x for x in item_neighbors if x != item]
                    neighbors[int(item)] += item_neighbors

        # remove duplicates
        for item in neighbors:
            neighbors[int(item)] = set(neighbors[int(item)])

        CSP.__init__(self, None, domains, neighbors,
                     self.different_values_constraint)