77 lines
2 KiB
Python
77 lines
2 KiB
Python
|
target = 2020
|
||
|
input_file = "/tmp/aocinput"
|
||
|
|
||
|
def find_sum_of_two():
|
||
|
large_n = []
|
||
|
small_n = []
|
||
|
|
||
|
with open(input_file) as file:
|
||
|
line = file.readline()
|
||
|
while line and line != "\n":
|
||
|
halftarget_count = 0
|
||
|
|
||
|
number = int(line)
|
||
|
if number > target/2:
|
||
|
large_n.append(number)
|
||
|
elif number == target/2:
|
||
|
halftarget_count += 1
|
||
|
else:
|
||
|
small_n.append(number)
|
||
|
|
||
|
if halftarget_count == 2:
|
||
|
print(f"Found a sum : {target/2}*2 = {target}\nAnswer is {(target/2)**2}")
|
||
|
break
|
||
|
|
||
|
line = file.readline()
|
||
|
|
||
|
for big_one in large_n:
|
||
|
complement = target-big_one
|
||
|
if complement in small_n:
|
||
|
print(f"Found a sum : {big_one}+{complement} = {target}\nAnswer is {big_one*complement}")
|
||
|
return
|
||
|
|
||
|
print("No sum found that can reach {target}")
|
||
|
|
||
|
def sum_search(target_sum, inputs):
|
||
|
lower = []
|
||
|
upper = []
|
||
|
|
||
|
for num in inputs:
|
||
|
if num < target_sum/2:
|
||
|
lower.append(num)
|
||
|
else:
|
||
|
upper.append(num)
|
||
|
|
||
|
search_list = lower if len(lower) < len(upper) else upper
|
||
|
iter_list = upper if len(lower) < len(upper) else lower
|
||
|
|
||
|
for num in iter_list:
|
||
|
if target_sum - num in search_list:
|
||
|
return num, target_sum-num
|
||
|
|
||
|
return False
|
||
|
|
||
|
|
||
|
def find_sum_of_three():
|
||
|
data = []
|
||
|
subtracted_to_target = []
|
||
|
with open(input_file) as file:
|
||
|
line = file.readline()
|
||
|
while line and line != "\n":
|
||
|
data.append(int(line))
|
||
|
subtracted_to_target.append((target-data[-1],data[-1]))
|
||
|
|
||
|
line = file.readline()
|
||
|
|
||
|
data.sort()
|
||
|
|
||
|
for sub_target in subtracted_to_target:
|
||
|
result = sum_search(sub_target[0],data)
|
||
|
if result:
|
||
|
print(f"Sum found : {result[0]}+{result[1]}+{sub_target[1]} = {target}\nResult is {result[0]*result[1]*sub_target[1]}")
|
||
|
return
|
||
|
|
||
|
print("No sum found")
|
||
|
|
||
|
|