aoc/2021/03/03.py
2021-12-07 23:41:35 -06:00

80 lines
1.6 KiB
Python

report = []
with open("input.txt") as f:
lines = f.read().split('\n')
for line in lines:
report.append(line)
gamma = ''
for i in range(len(report[0])):
ones_count = 0
for number in report:
if number[i] == '1':
ones_count += 1
half = len(report) / 2
if ones_count > half:
gamma += '1'
else:
gamma += '0'
power = 2 ** len(gamma) - 1
gamma = int(gamma, 2)
epsilon = power - gamma
part1 = gamma * epsilon
print(part1)
o2_candidates = set()
co2_candidates = set()
for number in report:
o2_candidates.add(number)
co2_candidates.add(number)
for i in range(len(report[0])):
if len(o2_candidates) == 1:
break
# first pass: count the bits in each position
ones_count = 0
zeros_count = 0
for number in o2_candidates:
if number[i] == '0':
zeros_count += 1
else:
ones_count += 1
# Keep 1, unless 0 is more common.
if zeros_count > ones_count:
keep = '0'
else:
keep = '1'
# second pass: filter out the candidates
for number in o2_candidates.copy():
if number[i] != keep:
o2_candidates.remove(number)
for i in range(len(report[0])):
if len(co2_candidates) == 1:
break
# first pass: count the bits in each position
ones_count = 0
zeros_count = 0
for number in co2_candidates:
if number[i] == '0':
zeros_count += 1
else:
ones_count += 1
# Keep 0, unless 1 is less common.
if ones_count < zeros_count:
keep = '1'
else:
keep = '0'
# second pass: filter out the candidates
for number in co2_candidates.copy():
if number[i] != keep:
co2_candidates.remove(number)
o2 = int(o2_candidates.pop(), 2)
co2 = int(co2_candidates.pop(), 2)
part2 = o2 * co2
print(part2)