Skip to content

Instantly share code, notes, and snippets.

@maxplomer
Created September 14, 2014 23:00
Show Gist options
  • Save maxplomer/7789df5f428582478bf2 to your computer and use it in GitHub Desktop.
Save maxplomer/7789df5f428582478bf2 to your computer and use it in GitHub Desktop.
sum of pairs
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