Created
September 14, 2014 23:00
-
-
Save maxplomer/7789df5f428582478bf2 to your computer and use it in GitHub Desktop.
sum of pairs
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 sum_of_pairs(arr) | |
max_length = 0 #max length of subset | |
#go through all subsets | |
for i in 0..(arr.size - 2) | |
for j in (i + 1)..(arr.size - 1) | |
sub_arr = arr[i..j] | |
sub_arr_length = sub_arr.length | |
if is_good?(sub_arr) | |
max_length = sub_arr_length if sub_arr_length > max_length | |
end | |
end | |
end | |
max_length | |
end | |
def is_good?(subarr) | |
arr_sum = subarr.inject(:+) | |
return false unless arr_sum % (subarr.size / 2) == 0 | |
arr_ave = arr_sum / (subarr.size / 2) | |
until subarr.empty? | |
dig = subarr.shift | |
dig_pair = arr_ave - dig | |
index = subarr.each_index.select{|i| subarr[i] == dig_pair} | |
subarr.delete_at(index[0]) unless index.empty? | |
return false if index.empty? | |
end | |
true | |
end | |
#p is_good?([1,4,2,3]) | |
#p is_good?([1, 4]) | |
p sum_of_pairs([1, 4, 2, 3, 8, 10] ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment