-
-
Save catpad/acedf5b07df6463e4ebbe9b21c95e640 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import itertools | |
W, H = 4, 4 | |
def create_matrices(): | |
# N -> matrix | |
matrices = {} | |
perm = ["".join(seq) for seq in itertools.product("01", repeat=W*H)] | |
for index, p in enumerate(perm): | |
i = 0 | |
# Initialize a new matrix | |
matrix = [[0 for x in range(W)] for y in range(H)] | |
for row in range(H): | |
for col in range(W): | |
matrix[row][col] = int(p[i]) # matrix consists of integer 0 and 1 | |
i += 1 | |
# Matrix is ready | |
matrices[index] = matrix | |
return matrices | |
def neighbors(matrix, i, j): | |
total = 0 | |
for x in range(i-1, i+2): | |
for y in range(j-1, j+2): | |
if x == i and y == j: continue | |
#Circular board | |
""" | |
if x == -1: x = W-1 | |
if y == -1: y = H-1 | |
if x == W: x = 0 | |
if y == H: y = 0 | |
""" | |
if x == -1: continue | |
if y == -1: continue | |
if x == W: continue | |
if y == H: continue | |
total += matrix[x][y] | |
return total | |
def check_future(present, future): | |
for i in range(W): | |
for j in range(H): | |
nbrs = neighbors(future, i, j) | |
if present[i][j] == 1: | |
# This cell is alive; it will stay alive if in the future it has 2 or 3 neighbors | |
if (nbrs == 2 or nbrs == 3) and future[i][j] == 1: | |
# good | |
continue | |
# This cell is alive; it will die from loneliness or overpopulation | |
elif (nbrs < 2 or nbrs > 3) and future[i][j] == 0: | |
# good | |
continue | |
else: | |
return False | |
else: | |
# This cell is not alive; it will be born if in the future it has exactly 3 neighbors | |
if nbrs == 3 and future[i][j] == 1: | |
# good | |
continue | |
else: | |
return False | |
return True | |
all_possible_futures = all_possible_presents = create_matrices() | |
for pkey in all_possible_presents.keys(): | |
present = all_possible_presents[pkey] | |
# Check all candidates | |
for fkey in all_possible_futures: | |
future = all_possible_futures[fkey] | |
if (check_future(present, future)): | |
print("Possible cadidate for (" + str(pkey) + ") " + | |
str(present) + " -> (" + str(fkey) + ") " + str(future)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment