Created
June 20, 2011 13:23
-
-
Save mleszcz/1035594 to your computer and use it in GitHub Desktop.
complementary pairs of array items
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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