advent/2021/3/2.py

61 lines
1.2 KiB
Python

#!/usr/bin/env python3
files = [i.rstrip() for i in open("input").readlines()]
def oxy(bits):
zero = 0
one = 0
for i in bits:
if i == "0":
zero += 1
else:
one += 1
if zero > one:
return 0
elif one > zero:
return 1
elif one == zero:
return 1
def co2(bits):
zero = 0
one = 0
for i in bits:
if i == "0":
zero += 1
else:
one += 1
if zero < one:
return 0
elif one < zero:
return 1
elif one == zero:
return 0
def oxygen(fields):
buf = fields
for i in range(len(fields[0])):
testing = [j[i] for j in buf]
oxygenrating = oxy(testing)
buf = [j for j in buf if int(j[i]) == oxygenrating]
return buf
def carbdio(fields):
buf = fields
for i in range(len(fields[0])):
if len(buf) == 1: break
testing = [j[i] for j in buf]
print(buf, testing)
co2rating = co2(testing)
buf = [j for j in buf if int(j[i]) == co2rating]
return buf
oxygenreal = int(''.join(oxygen(files)), base=2)
carbdioreal = int(''.join(carbdio(files)), base=2)
print(oxygenreal, carbdioreal, oxygenreal * carbdioreal)