my solutions for advent of code 2022
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.6 KiB

2 years ago
beacons = []
sensors = []
CoveredPoints = {}
maxcoord = 4000000
def loop(vectors):
for j in range(len(vectors)):
for i in range(len(vectors)):
if j != i:
if vectors[j][0] in range (vectors[i][0], vectors[i][1]) or vectors[i][0] in range (vectors[j][0], vectors[j][1]):
tempSt = min(vectors[j][0],vectors[i][0])
tempEn = max(vectors[j][1],vectors[i][1])
vectors.append((tempSt, tempEn))
vectors.pop(max(i, j))
vectors.pop(min(i, j))
return False, vectors
return True, vectors
def loop2(vectors):
if len(vectors) > 2:
for i in range(len(vectors) - 1):
if vectors[i][1] == vectors[i+1][0] or vectors[i][1] + 1== vectors[i+1][0]:
vectors.append((vectors[i][0], vectors[i+1][1]))
vectors.pop(i+1)
vectors.pop(i)
vectors = sorted(vectors)
return False, vectors
elif len(vectors) == 2:
if vectors[0][1] == vectors[1][0] or vectors[0][1] + 1== vectors[1][0]:
vectors = [(vectors[0][0], vectors[1][1])]
return True, vectors
return True, vectors
with open('input15.txt','r') as f:
inp = f.read().splitlines(keepends=False)
for line in inp:
tempA, tempB = line.split(': closest beacon is at x=')
tempA = tempA.replace('Sensor at x=', '')
tempA = tempA.split(', y=')
sensors.append(tuple(map(int, tempA)))
tempB = tempB.split(', y=')
beacons.append(tuple(map(int, tempB)))
for i in range(len(sensors)):
print('checking sensor', i, 'out of', len(sensors) - 1)
(sensX, sensY) = sensors[i]
(beacX, beacY) = beacons[i]
distance = (max(sensX, beacX) - min(sensX, beacX)) + (max(sensY, beacY) - min(sensY, beacY))
for j in range(distance + 1):
CoveredPoints.setdefault((sensY-j), [])
CoveredPoints.setdefault((sensY+j), [])
CoveredPoints[sensY-j].append((sensX - (distance - j), sensX + (distance - j)))
CoveredPoints[sensY+j].append((sensX - (distance - j), sensX + (distance - j)))
tempA = []
for vc in CoveredPoints:
done = False
vectors = CoveredPoints[vc].copy()
while not done:
done, vectors = loop(vectors)
done = False
vectors = sorted(vectors)
while not done:
done, vectors = loop2(vectors)
CoveredPoints[vc] = vectors
for i in range(maxcoord + 1):
line = CoveredPoints[i]
if len(line) > 1:
coordX = line[0][1] + 1
coordY = i
frequency = coordX * 4000000 + coordY
print('Beacon found y =',coordY,'x =',coordX,'frequency =', frequency)