Advent-of-Code/2021/3/main2.py

134 lines
3.4 KiB
Python
Raw Permalink Normal View History

bits = []
gamma = 0
epsilon = 0
gamma_str = ''
epsilon_str = ''
lines = []
oxy = []
co2 = []
def NarrowDown(oxy, co2, index):
# # DEBUG(dev):
# print len(oxy), ", ", len(co2)
# print ""
if(len(oxy) > 1): # if we already found it, just move along
# Look at `index` in each remaining value; count how many have a ZERO vs. a ONE:
num_ones = 0
num_zeros = 0
new_oxy = []
for i,o in enumerate(oxy):
if(o[index] == '1'):
num_ones = num_ones + 1
else:
num_zeros = num_zeros + 1
# Oxy needs the majority, keeping the ONEs if there's a tie:
if(num_ones < num_zeros):
for o in oxy:
if(o[index] == '0'):
new_oxy.append(o)
else:
for o in oxy:
if(o[index] == '1'):
new_oxy.append(o)
oxy = list(new_oxy)
if(len(co2) > 1): # if we already found it, just move along
# Look at `index` in each remaining value; count how many have a ZERO vs. a ONE:
num_ones = 0
num_zeros = 0
new_co2 = []
for i,o in enumerate(co2):
if(o[index] == '1'):
num_ones = num_ones + 1
else:
num_zeros = num_zeros + 1
# Co2 needs the minority, keeping the ZEROs if there's a tie:
if(num_ones < num_zeros):
for c in co2:
if(c[index] == '1'):
new_co2.append(c)
else:
for c in co2:
if(c[index] == '0'):
new_co2.append(c)
co2 = list(new_co2)
# if we're down to one number in BOTH LISTS, we're done
if(len(oxy) == 1 and len(co2) == 1):
return oxy[0],co2[0]
# otherwise, pass both remaining lists on, move over one index, and continue narrowing down:
return NarrowDown(oxy, co2, (index + 1))
#### MAIN EXECUTION ####
with open('data', 'r') as fp:
for line in fp:
lines.append(line.strip())
# NOTE(dev): We assume all lines are the same length
for i in range(0, len(lines[0])):
bits.append(0)
# # DEBUG(dev):
# test = fp.readline()
# for i in range(0, len(test)):
# print test[i]
for line in lines:
for i in range(0, len(line.strip())):
if(line[i] == '1'):
bits[i] = bits[i] + 1
else:
bits[i] = bits[i] - 1
for i in range(0, len(bits)):
ch = '1'
if(bits[i] < 0):
ch = '0'
gamma_str = gamma_str + ch
# # DEBUG(dev):
# for i in range(1, len(gamma_str)+1):
# print gamma_str[-i]
# NOTE(dev): Have to do (i+1) because we're going backwards, which starts at -1
for i in range(0, len(gamma_str)):
if(gamma_str[-(i+1)] == '1'):
gamma = gamma + pow(2,i)
else:
epsilon = epsilon + pow(2,i)
# print " bits: ", bits
print " gamma: ", gamma
print "epsilon: ", epsilon
print " POWER: ", gamma * epsilon
oxy = list(lines)
co2 = list(lines)
oxy_str,co2_str = NarrowDown(oxy, co2, 0)
oxy_value = 0
co2_value = 0
# convert binary string representation to decimal
for i in range(0, len(oxy_str)):
if(oxy_str[-(i+1)] == '1'):
oxy_value = oxy_value + pow(2,i)
# convert binary string representation to decimal
for i in range(0, len(co2_str)):
if(co2_str[-(i+1)] == '1'):
co2_value = co2_value + pow(2,i)
print "oxy: ", oxy_value
print "co2: ", co2_value
print " : ", oxy_value * co2_value