Skip to content

Instantly share code, notes, and snippets.

@mleszcz
Created June 20, 2011 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mleszcz/1035594 to your computer and use it in GitHub Desktop.
Save mleszcz/1035594 to your computer and use it in GitHub Desktop.
complementary pairs of array items
def dups(arr, i, j)
l_dups, r_dups = 0, 0
i.upto(j) do |n|
break if arr[n] != arr[i]
l_dups +=1
end
j.downto(i) do |n|
break if arr[n] != arr[j]
r_dups += 1
end
[l_dups, r_dups]
end
def complementary_pairs(k, arr)
arr.sort!
p arr
i, j, count = 0, arr.size-1, 0
while i <= j
if arr[i] + arr[j] == k
# finish - center of an array
if arr[i] == arr[j]
count += (1+j-i)**2
break
else
# duplicate pairs - for [i,-,...,-,j]
if i+2 < j and arr[i+1] == arr[i] and arr[j-1] == arr[j]
l_dups, r_dups = dups(arr, i, j)
count += l_dups * r_dups * 2
i += l_dups + 1
j -= r_dups - 1
elsif i != j and arr[j-1] == arr[j]
count += 2
j -= 1
else
count += 2
i += 1
end
end
elsif arr[i] + arr[j] < k
i += 1
else
j -= 1
end
end
count
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment