adventofcode-2020/11/part2

75 lines
1.7 KiB
Plaintext
Raw Normal View History

2020-12-13 20:58:10 +01:00
#!/usr/bin/python3
from pprint import pprint
def read_area():
area = []
with open("input") as fh:
for ln in fh:
area.append(list(ln.strip()))
return area
def neighbours(area, i, j):
count = 0
for i1 in (-1, 0, 1):
if i + i1 < 0:
continue
if i + i1 >= len(area):
continue
for j1 in (-1, 0, 1):
if i1 == j1 == 0:
continue
if j + j1 < 0:
continue
if j + j1 >= len(area[i + i1]):
continue
n = 1
while True:
i2 = i + n * i1
if not (0 <= i2 < len(area)):
break
j2 = j + n * j1
if not (0 <= j2 < len(area[i2])):
break
if area[i2][j2] == "L":
break
if area[i2][j2] == "#":
count += 1
break
n += 1
return count
def new_occ(area, i, j):
if area[i][j] == ",":
return "."
if area[i][j] == "L" and neighbours(area, i, j) == 0:
return "#"
if area[i][j] == "#" and neighbours(area, i, j) >= 5:
return "L"
return area[i][j]
def next_tick(area):
new_area = []
for i in range(len(area)):
new_row = []
for j in range(len(area[i])):
new_row.append(new_occ(area, i, j))
new_area.append(new_row)
return new_area
def count_occupied(area):
sum = 0
for row in area:
for seat in row:
sum += seat == "#"
return sum
area = read_area()
while True:
new_area = next_tick(area)
if new_area == area:
break
area = new_area
print(count_occupied(area))