1
0
Fork 0

2021 day 3

This commit is contained in:
Lucidiot 2021-12-04 00:08:17 +01:00
parent 4e5c92b4f5
commit 719bf0b6a2
Signed by: lucidiot
GPG Key ID: 3358C1CA6906FB8D
2 changed files with 32 additions and 1 deletions

31
2021/3/day3.py Normal file
View File

@ -0,0 +1,31 @@
#!/usr/bin/env python3
from collections import Counter
from functools import reduce
import fileinput
def tonumber(num_list):
return reduce(lambda number, digit: (number << 1) + digit, num_list)
matrix = sorted(map(lambda line: list(map(int, line.strip())), fileinput.input()))
zipped_matrix = list(zip(*matrix))
gamma = tonumber([numbers.count(1) >= len(numbers) / 2 for numbers in zipped_matrix])
epsilon = ~gamma & (2 ** len(zipped_matrix) - 1)
print(gamma * epsilon)
def binary_search(criteria):
min, max = 0, len(matrix)
i = 0
while (max - min) > 1 and i < len(zipped_matrix):
slice = zipped_matrix[i][min:max]
zeroes, ones = slice.count(0), slice.count(1)
if criteria(zeroes, ones):
min += zeroes
else:
max -= ones
i += 1
assert (max - min) == 1
return tonumber(matrix[min])
oxygen = binary_search(lambda zeroes, ones: ones >= zeroes)
co2 = binary_search(lambda zeroes, ones: ones < zeroes)
print(oxygen * co2)

View File

@ -13,7 +13,7 @@ is acceptable; anything goes as long as I solve it myself!
15 16 17 18 19 20 21
1 ██ ██ ██ ██ ██ ██
2 ██ ██ ██ ██ ██ ██
3 ██ ██ ██ ██ ██
3 ██ ██ ██ ██ ██ ██
4 ██ ██ ██ ██
5 ██ ██ ██ ██
6 ██ ██ ██