Compare commits

..

2 commits

Author SHA1 Message Date
32660da53e 2021 day3/python: add solution 2021-12-03 07:13:45 +01:00
0434ce436e 2020 day3: add data 2021-12-03 07:13:26 +01:00
3 changed files with 1040 additions and 0 deletions

2
2021/data/day3.expected Normal file
View file

@ -0,0 +1,2 @@
3895776
7928162

1000
2021/data/day3.input Normal file

File diff suppressed because it is too large Load diff

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))