after reading about Finding three elements in an array whose sum is closest to a given number, this is my attempt at implementing such algorithm
def findThree(seq, goal):
# initialize the differences
goalDifference = float("inf")
dl = -1
dr = -1
dx = -1
for x in range(len(seq)-1):
left = x+1
right = len(seq)-1
while (left < right):
# if the absolute value of the previous set and the goal is less than the current goalDifference,
# keep track of the new set
if(abs(goal - (seq[left] + seq[right] + seq[x])) < goalDifference):
dl = left
dr = right
dx = x
tmp = seq[left] + seq[right] + seq[x]
if tmp > goal:
right -= 1
elif tmp < goal:
left += 1
else:
return [seq[left],seq[right],seq[x]]
# if no match is found, return the closest set
return [seq[dl],seq[dr], seq[dx]]
The algorithm works great for finding exact solutions, given
arr = [89, 120, 140, 179, 199, 259, 259, 259, 320, 320]
findThree(arr, 349) // want to get [120, 140, 89]
>> [120, 140 89] // success
findThree(arr, 439) // want to get [140, 179, 120]
>> [140, 179,120] // success
however, when I want to see if it'll return the closest, it returns
findThree(arr, 350) // only 1 more than 349, should return [120, 140, 89]
>> [320, 320, 259] // fail
findThree(arr, 440) // only 1 more than 439, should return [140, 179, 120]
>> [320, 320, 259] // fail
it appears that when I want it to return the "cloest" element, it always returns [320, 320, 259]. I've been looking at the code for a few hours now, but still can't figure out what's wrong.