2021 day3/python: add solution

This commit is contained in:
Xiretza 2021-12-03 07:13:45 +01:00
parent a5e00087f2
commit 42f425198b

38
2021/day3/day3.py Executable file
View file

@ -0,0 +1,38 @@
#!/usr/bin/env python
import sys
from collections import Counter
def most_common(ns, pos):
c = Counter(n[pos] for n in ns)
num_zeros = c['0']
num_ones = c['1']
if num_ones >= num_zeros:
return '1'
else:
return '0'
def least_common(ns, pos):
return '0' if most_common(ns, pos) == '1' else '1'
def find_criteria(ns, criteria):
ns = ns
i = 0
while len(ns) > 1:
x = criteria(ns, i)
ns = [n for n in ns if n[i] == x]
i += 1
return ns[0]
if __name__ == '__main__':
lines = [line.strip() for line in sys.stdin.readlines()]
line_len = len(lines[0])
gamma = ''.join(most_common(lines, n) for n in range(line_len))
epsilon = ''.join(least_common(lines, n) for n in range(line_len))
print(int(gamma, 2) * int(epsilon, 2))
oxygen_rating = find_criteria(lines, most_common)
co2_rating = find_criteria(lines, least_common)
print(int(oxygen_rating, 2) * int(co2_rating, 2))