Created
December 11, 2020 05:39
-
-
Save redspider/6d12f279fd842c48204c2441500229f1 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
# I went for speed on this one, it was a mess | |
HEIGHT = len(INPUT.split("\n")) | |
WIDTH = len(INPUT.split("\n")[0]) | |
grid = dict() | |
for y, line in enumerate(INPUT.split("\n")): | |
for x, c in enumerate(line): | |
grid[(x, y)] = c | |
def count_occupied(grid, x, y): | |
count = 0 | |
for xo in [-1, 0, 1]: | |
for yo in [-1, 0, 1]: | |
if xo == 0 and yo == 0: | |
continue | |
if grid.get((x + xo, y + yo)) == '#': | |
count += 1 | |
return count | |
def look_vector(grid, x,y,xv,yv): | |
x += xv | |
y += yv | |
while x >= 0 and y >= 0 and x < WIDTH and y < HEIGHT: | |
if grid[x,y] == '#': | |
return True | |
if grid[x,y] == 'L': | |
return False | |
x += xv | |
y += yv | |
return False | |
def count_occupied_sightlines(grid, x, y): | |
count = 0 | |
for xo in [-1, 0, 1]: | |
for yo in [-1, 0, 1]: | |
if xo == 0 and yo == 0: | |
continue | |
if look_vector(grid, x, y, xo, yo): | |
count += 1 | |
return count | |
def iterate(grid): | |
new_grid = dict() | |
for x,y in grid.keys(): | |
c = grid[(x,y)] | |
if c == '.': | |
new_grid[x,y] = c | |
if c == 'L': | |
if count_occupied_sightlines(grid, x, y) == 0: | |
new_grid[x,y] = '#' | |
else: | |
new_grid[x,y] = c | |
if c == '#': | |
if count_occupied_sightlines(grid, x, y) >= 5: | |
new_grid[x, y] = 'L' | |
else: | |
new_grid[x, y] = c | |
return new_grid | |
def print_grid(grid): | |
for y in range(0, HEIGHT): | |
line = "" | |
for x in range(0, WIDTH): | |
line += grid[x,y] | |
print(line) | |
print() | |
def grid_equal(grid1, grid2): | |
for x,y in grid1: | |
if grid1[x,y] != grid2[x,y]: | |
return False | |
return True | |
def count_occupied_seats(grid): | |
return len([v for v in grid.values() if v == '#']) | |
equal = False | |
while not equal: | |
new_grid = iterate(grid) | |
equal = grid_equal(grid, new_grid) | |
print_grid(grid) | |
print(equal) | |
grid = new_grid | |
print(count_occupied_seats(grid)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment