day 3 alt
This commit is contained in:
parent
09c269c9f2
commit
437985b214
38
3/b_better.py
Normal file
38
3/b_better.py
Normal file
@ -0,0 +1,38 @@
|
||||
width = 12
|
||||
|
||||
with open("input.txt") as f:
|
||||
lines = [int(i.strip(), 2) for i in f.readlines()]
|
||||
|
||||
|
||||
def count_digits(ar, pos):
|
||||
zeros = 0
|
||||
ones = 0
|
||||
|
||||
for num in ar:
|
||||
if num & (1 << (width - pos - 1)):
|
||||
ones += 1
|
||||
else:
|
||||
zeros += 1
|
||||
|
||||
return zeros, ones
|
||||
|
||||
|
||||
def filter_by_digit(lines, position, value):
|
||||
return [i for i in lines if int(bool(i & (1 << (width - position - 1)))) == value]
|
||||
|
||||
|
||||
def filter_by(nums, func):
|
||||
position = 0
|
||||
while len(nums) > 1:
|
||||
zeros, ones = count_digits(nums, position)
|
||||
digit = func(zeros, ones)
|
||||
nums = filter_by_digit(nums, position, digit)
|
||||
position += 1
|
||||
|
||||
return nums[0]
|
||||
|
||||
|
||||
oxy = filter_by(lines, lambda zeros, ones: 1 if ones >= zeros else 0)
|
||||
co2 = filter_by(lines, lambda zeros, ones: 1 if ones < zeros else 0)
|
||||
|
||||
print(oxy * co2)
|
Loading…
Reference in New Issue
Block a user