re: AoC Day 6: Chronal Coordinates VIEW POST

This is my least favorite code I may have ever written. Need to refactor.

Part 1

from collections import Counter

with open('input.txt', 'r') as f:
coords = []
max_x = 0
max_y = 0
for line in f:
line = [int(i) for i in line.strip().split(', ')]
if line > max_x: max_x = line
if line > max_y: max_y = line
coords.append((line, line,))

matrix = [[(0, 0) for i in range(max_x + 2)] for n in range(max_y + 2)]
for idx, (x, y) in enumerate(coords):
matrix[x][y] = (idx+1, 0,)
for r_idx, row in enumerate(matrix):
for c_idx, col in enumerate(row):
dist = abs(x - r_idx) + abs(y - c_idx)
if col == 0 or dist < col:
matrix[r_idx][c_idx] = (idx+1, dist,)
elif dist == col and col != idx+1:
matrix[r_idx][c_idx] = (None, dist,)

matrix = [[i for i in sublist] for sublist in matrix]
flipped_matrix = matrix[::-1]
to_filter = set(matrix + matrix[-1] + flipped_matrix + flipped_matrix[-1])
list_matrix = []

for row in matrix:
for col in row:
if col not in to_filter:
list_matrix.append(col)

print(Counter(list_matrix).most_common(1))

part 2

from collections import Counter

with open('input.txt', 'r') as f:
coords = []
max_x = 0
max_y = 0
for line in f:
line = [int(i) for i in line.strip().split(', ')]
if line > max_x: max_x = line
if line > max_y: max_y = line
coords.append((line, line,))

n_regions = 0
matrix = [[(0, 0) for i in range(max_x + 2)] for n in range(max_y + 2)]
for r_idx, row in enumerate(matrix):
for c_idx, col in enumerate(row):
total_dist = 0
for idx, (x, y) in enumerate(coords):
dist = abs(x - r_idx) + abs(y - c_idx)
total_dist += dist
if total_dist < 10000:
n_regions += 1

print(n_regions)
code of conduct - report abuse  