Pages

Search This Blog

December 30, 2012

sum of pairs of elements in array equal to other element in the array

# find all the pairs that sum up to another
# element in array

# Algorithm: ( is there one :) )
# Sort the elements in decreasing order
# Start from the first element, inspect all the elements
# after the element chosen, for the eligible pair
# Once we reach first element, we are done !

#a=[2,3,4,5,6]
a=[5,7,1,2,3,4,6,8,12,14,13,10]

a.sort()
a.reverse()

for i in xrange(len(a)):
    j=i+1
    k=len(a)-1
    while j<k:
        if a[i]==a[j]+a[k]:
            print a[i], \' => \', a[j], \',\', a[k]
            j=j+1 # assuming elements don\'t repeat
            k=k-1
        elif a[i]<a[j]+a[k]:
            j=j+1
        else:
            k=k-1

No comments:

Post a Comment