Skip to content

Instantly share code, notes, and snippets.

@spielkind
Last active December 3, 2021 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spielkind/405d34127a1740b8eb0babb5441007c1 to your computer and use it in GitHub Desktop.
Save spielkind/405d34127a1740b8eb0babb5441007c1 to your computer and use it in GitHub Desktop.
#!/bin/python
with open('day3.txt') as f:
bitslist = [list(map(int, line.strip())) for line in f]
def column(bitslist, location):
return [bits[location] for bits in bitslist]
def bitcount(bitslist, location):
zero_count = column(bitslist, location).count(0)
one_count = len(bitslist) - zero_count
return [zero_count, one_count]
def all_bitscount(bitslist):
return [bitcount(bitslist, i) for i in range(len(bitslist[0]))]
def to_int(binary):
return int(''.join(map(str, binary)), 2)
overall = all_bitscount(bitslist)
gamma = [1 if v0 > v1 else 0 for v0, v1 in overall]
epsilon = [1 if v0 < v1 else 0 for v0, v1 in overall]
print('Part One:', to_int(gamma) * to_int(epsilon))
def value_at_position(i, bit):
return lambda bits: bits[i] == bit
def getvalues(value, condition):
for i in range(len(value[0])):
count = bitcount(value, i)
wanted_bit = condition(count[1],count[0])
value = list(filter(value_at_position(i, wanted_bit), value))
if len(value) == 1:
return value[0]
oxy = getvalues(bitslist, lambda a, b: 1 if a >= b else 0)
co2 = getvalues(bitslist, lambda a, b: 0 if b <= a else 1)
print('Part Two:',to_int(oxy)*to_int(co2))
@spielkind
Copy link
Author

spielkind commented Dec 3, 2021

credits to @Tomalak who helped me a lot with that, and answered all my stupid questions :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment