Created
December 3, 2021 18:58
-
-
Save albertein/ad2eb77edda8e15132bf31fc0df39a8d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if __name__ == '__main__': | |
with open('input.txt') as data: | |
one_counts = [] | |
total = 0 | |
for line in data: | |
line = line.strip() | |
if len(one_counts) == 0: | |
one_counts = [0] * len(line) | |
for idx, char in enumerate(line): | |
if char == '1': | |
# One counts is considered to be aligned with less significant bit | |
# to most significant. Since input is from most significant to less | |
# significant we need to flip the direction when filling one_counts. | |
one_counts[len(one_counts) - 1 - idx] += 1 | |
total += 1 | |
gamma = 0 | |
# one_counts contains the counts of 1s on each bit position. | |
# To calculate gamma we need to get a binary number formed by the | |
# most common digit on each position, so if one_count at index X | |
# is >= than half the numbers the bit on that position is 1, otherwise | |
# we skip it since the most common digit is 0. | |
for idx, count in enumerate(one_counts): | |
if count >= total / 2: | |
gamma += 2 ** idx | |
# Epsilon composed by the less common bits, so we only need to negate | |
# gamma and apply a mask on the bit leght (2^length - 1). | |
epsilon = ~gamma & (2 ** (len(one_counts)) - 1) | |
print(gamma, epsilon, gamma * epsilon) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment