Skip to content

Instantly share code, notes, and snippets.

@pjhoberman
Created December 11, 2020 21:40
Show Gist options
  • Save pjhoberman/ffd1266757dfb2adc66ecf9c84d09fff to your computer and use it in GitHub Desktop.
Save pjhoberman/ffd1266757dfb2adc66ecf9c84d09fff to your computer and use it in GitHub Desktop.
from collections import Counter
with open('data.txt') as file:
data = file.read().splitlines()
def get_adjacent_seats(row, col, _data):
previous_row = None
next_row = None
previous_col = None
next_col = None
# is there a previous row?
if row > 0:
previous_row = row - 1
# is there a next row?
if row < len(_data) - 1:
next_row = row + 1
# is there a previous col?
if col > 0:
previous_col = col - 1
# is there a next col?
if col < len(_data[0]) - 1:
next_col = col + 1
adjacents = []
if previous_row is not None:
if previous_col:
adjacents.append(_data[previous_row][previous_col])
adjacents.append(_data[previous_row][col])
if next_col is not None:
adjacents.append(_data[previous_row][next_col])
if previous_col is not None:
adjacents.append(_data[row][previous_col])
if next_col is not None:
adjacents.append(_data[row][next_col])
if next_row is not None:
if previous_col is not None:
adjacents.append(_data[next_row][previous_col])
adjacents.append(_data[next_row][col])
if next_col is not None:
adjacents.append(_data[next_row][next_col])
return adjacents
def make_moves(row, col, previous_pass, new_data):
if len(new_data) <= row:
new_data.append([])
if previous_pass[row][col] == ".":
new_data[row].append(".")
elif previous_pass[row][col] == "L" and "#" not in get_adjacent_seats(row, col, previous_pass):
new_data[row].append("#")
elif previous_pass[row][col] == "#" and Counter(get_adjacent_seats(row, col, previous_pass))["#"] >= 4:
new_data[row].append("L")
else:
new_data[row].append(previous_pass[row][col])
return new_data
def print_data(d):
for row in d:
print("".join(row))
print("\n")
def run_it(_print=False):
previous_pass = data
i = 1
while True:
new_data=[[]]
for row in range(len(data)):
for col in range(len(data[0])):
new_data = make_moves(row, col, previous_pass, new_data)
if _print:
print(f"pass {i}")
i += 1
print_data(new_data)
if new_data == previous_pass:
break
previous_pass = new_data
# print_data(new_data)
return Counter("".join(["".join(row) for row in new_data]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment