Day 11 (part 2 more beautiful / method of part 1 is faster)

This commit is contained in:
Sebastian Seedorf
2020-12-12 13:49:48 +01:00
parent 4919e2fc92
commit be9b398dc5

View File

@@ -1,50 +1,42 @@
import numpy as np import numpy as np
from day11.common import char_to_int from day11.common import char_to_int
lines = np.array([[char_to_int(x) for x in line.strip()] for line in open("input.txt")], dtype=np.byte) seats = np.array([[char_to_int(x) for x in line.strip()] for line in open("input.txt")], dtype=np.byte)
shape = lines.shape
RAYS = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] RAYS = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
occupied = -1
def find_neighbor(idx, ray):
idx = tuple(map(sum, zip(idx, ray)))
while 0 <= idx[0] < seats.shape[0] and 0 <= idx[1] < seats.shape[1]:
if seats[idx] == -1:
return 0
elif seats[idx] == 0:
idx = tuple(map(sum, zip(idx, ray)))
continue
else:
return 1
else:
return 0
last = -1
while True: while True:
curr = np.count_nonzero(lines == 1) new_occupied = np.count_nonzero(seats == 1)
if curr == last: if occupied == new_occupied:
print(last)
break break
last = curr occupied = new_occupied
result = np.zeros_like(seats)
new = np.zeros_like(lines, dtype=np.byte) for idx, val in np.ndenumerate(seats):
for idx, val in np.ndenumerate(lines):
if val == 0: if val == 0:
continue continue
if val == -1: neighbors = sum(find_neighbor(idx, ray) for ray in RAYS)
found = False if val == -1 and neighbors == 0:
for ray in RAYS: result[idx] = 1
ray = np.array(ray) elif val == 1 and neighbors >= 5:
pos = np.array(idx) + ray result[idx] = -1
while 0 <= pos[0] < shape[0] and 0 <= pos[1] < shape[1]: else:
if lines[tuple(pos)] == 1: result[idx] = seats[idx]
found = True seats = result
break print(occupied)
elif lines[tuple(pos)] == -1:
break print(occupied)
pos = pos + ray
if found:
break
new[idx] = 1 if not found else -1
continue
if val == 1:
found = 0
for ray in RAYS:
ray = np.array(ray)
pos = np.array(idx) - ray
while 0 <= pos[0] < shape[0] and 0 <= pos[1] < shape[1]:
if lines[tuple(pos)] == 1:
found += 1
break
elif lines[tuple(pos)] == -1:
break
pos = pos - ray
new[idx] = -1 if found >= 5 else 1
lines = new