Skip to content

Instantly share code, notes, and snippets.

@orlp

orlp/ip_life.py Secret

Created March 29, 2017 18:34
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save orlp/fc1d85c9aa1737bb6851df881deea1e6 to your computer and use it in GitHub Desktop.
d = """
0101110100
0010101001
1011100110
0101111101
1001001111
1111001001
1011111010
0110011101
1001010100
0010111010
"""
d = [list(map(int, l.strip())) for l in d.strip().split("\n")]
p = MixedIntegerLinearProgram()
v = p.new_variable(binary=True)
w = len(d[0])
h = len(d)
for y in range(h):
for x in range(w):
neighbours = [(x + dx, y + dy)
for dx in [-1, 0, 1] for dy in [-1, 0, 1]
if 0 <= x + dx < w and 0 <= y + dy < h and not dx == dy == 0]
nsum = sum(v[n] for n in neighbours)
if d[y][x]:
born = v[(x, y, 's')]
p.add_constraint(2 + born <= nsum <= 3)
p.add_constraint(v[(x, y)] == 1 - born)
else:
overpop = v[(x, y, 'o')]
p.add_constraint(overpop * 4 <= nsum <= 1 + 7*overpop)
p.solve()
v = p.get_values(v)
l = [[int(v[(x, y)]) for x in range(w)] for y in range(h)]
for r in l:
print("".join(map(str, r)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment