Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Linked Objects solution in Uncategorized category for The Square Chest by Gamblore
class Cell:
def __init__(self, n):
self.n = n
self.x, self.y = divmod(n, 4)[::-1]
self.connections = []
def connect(self, other_cell):
self.connections.append(other_cell)
def connects_to(self, other_cell):
return other_cell in self.connections
def __eq__(self, cell):
if (isinstance(cell, Cell)):
return self.n == cell.n
elif (isinstance(cell, int)):
return self.n == cell
else:
raise TypeError
def __repr__(self):
return "Cell(%s) -> %s" % (self.n, len(self.connections))
def connects(cells, n, x_moves=0, y_moves=0):
cell = cells[n-1]
origin_number = cell.n
if (x_moves > 0):
for i in range(1, x_moves+1):
t_cell = Cell(origin_number + i)
if (cell.connects_to(t_cell)):
cell = cells[t_cell.n-1]
else:
return None
return True
if (y_moves > 0):
for i in range(1, y_moves+1):
t_cell = Cell(origin_number + i * 4)
if (cell.connects_to(t_cell)):
cell = cells[t_cell.n-1]
else:
return None
return True
return True
def checkio(lines_list):
"""Return the qantity of squares"""
cells = [ Cell(i+1) for i in range(16)]
lines = [sorted(x) for x in lines_list]
for i in range(len(lines)):
c1, c2 = cells[lines[i][0]-1], cells[lines[i][1]-1]
c1.connect(c2)
# can ignore the other direction because the values are sorted
square_count = 0
for y in range(3):
for x in range(3):
for size in range(1,4-max(x,y)):
if (connects(cells, y * 4 + x + 1, x_moves=size) and connects(cells, y * 4 + x + size + 1, y_moves=size) \
and connects(cells, y * 4 + x + 1, y_moves=size) and connects(cells, (y + size) * 4 + x + 1, x_moves=size)):
square_count += 1
return square_count
if __name__ == '__main__':
assert (checkio([[1,2],[3,4],[1,5],[2,6],[4,8],[5,6],[6,7],
[7,8],[6,10],[7,11],[8,12],[10,11],
[10,14],[12,16],[14,15],[15,16]]) == 3) , "First, from description"
assert (checkio([[1,2],[2,3],[3,4],[1,5],[4,8],
[6,7],[5,9],[6,10],[7,11],[8,12],
[9,13],[10,11],[12,16],[13,14],[14,15],[15,16]]) == 2), "Second, from description"
assert (checkio([[1,2], [1,5], [2,6], [5,6]]) == 1), "Third, one small square"
assert (checkio([[1,2], [1,5], [2,6], [5,9], [6,10], [9,10]]) == 0), "Fourth, it's not square"
assert (checkio([[16,15], [16,12], [15,11], [11,10],
[10,14], [14,13], [13,9]]) == 0), "Fifth, snake"
Nov. 9, 2012