0
0
Fork 0

Add D3P1 and D3P2

This commit is contained in:
Oliver-Akins 2021-12-29 22:31:46 -07:00
parent 7a10e3afd1
commit b0484acced
3 changed files with 174 additions and 0 deletions

33
day_03/python/part_1.py Normal file
View file

@ -0,0 +1,33 @@
with open("../input", "r") as file:
data = file.read().split("\n")
# Create an array that stores the number of 1's found in the corresponding bit
# position
ones_count = [0] * len(data[0])
# Run through all the data calculating the value of the bits
for diagnosis in data:
for i in range(len(diagnosis)):
if diagnosis[i] == "1":
ones_count[i] += 1
# Convert the bit counts into the correct binary for the two types of data we
# need
binary = ""
inverted_binary = ""
for count in ones_count:
if count > len(data) // 2:
binary += "1"
inverted_binary += "0"
else:
binary += "0"
inverted_binary += "1"
print(f"""Binary Before Inversion: {binary}
Binary After Inversion: {inverted_binary}
Value of Binary: {int(binary, 2)}
Value of Inverted Binary: {int(inverted_binary, 2)}
Binary * Inverted Binary = {int(binary, 2) * int(inverted_binary, 2)}""")

43
day_03/python/part_2.py Normal file
View file

@ -0,0 +1,43 @@
with open("../input", "r") as file:
data = file.read().split("\n")
def find_value(data, bit=0, sort="max"):
if len(data) == 1:
return data[0]
# keep track of each value that is associated with the bit value at the bit
# position, this is what gets passed to the recursive case
ones = []
zeros = []
# Run through all the data determining the bits needed
for d in data:
if d[bit] == "1": ones.append(d)
else: zeros.append(d)
new_bit = bit + 1
if sort == "max":
if len(ones) >= len(zeros):
return find_value(ones, new_bit, sort)
else:
return find_value(zeros, new_bit, sort)
else:
if len(ones) < len(zeros):
return find_value(ones, new_bit, sort)
else:
return find_value(zeros, new_bit, sort)
o2 = find_value(data)
co2 = find_value(data, sort="min")
print(f"""O2 binary: {o2}
CO2 binary: {co2}
O2 decimal: {int(o2, 2)}
CO2 decimal: {int(co2, 2)}
Life support value: {int(o2, 2) * int(co2, 2)}""")