=begin
For 2 arrays check if any pair
of numbers add up to 8
=end
#Questions
#Will I always expect numbers?
#Will the numbers always be integers? No foating numbers?
#Will the numbers all be positives?
#Is it all sorted?
#Assumptions
#Sorted and all positive integers
def first_return8?(arr)
#loop through the array and check each pairs
arr.each.with_index do |a, i|
new_arr = arr.select.with_index {|n, ind| ind != i }
new_arr.each do |n|
if a + n == 8
return true
break
end
end
end
return false
end
#puts first_return8?([1,2,3,4])
## first_return8? is bad. It has 0(N^2) and space complexity of O(N)
def second_return8?(arr, index_one = 0, index_two = arr.length-1)
#we start from the lowest and move index2 back if pair sum is too high because index_two is
# always the highest value in the array.
# We move the index1 up if pair sum is too low.
# We must ensure the movement doesnt overlap, hence the unless statement
unless index_one + 1 == index_two
sum = arr[index_one] + arr[index_two]
if sum == 8
return true
elsif sum < 8
return second_return8?(arr, index_one + 1, index_two)
else
return second_return8?(arr, index_one, index_two - 1)
end
end
if arr[index_one] + arr[index_two] == 8
return true
end
return false
end
puts second_return8?([1,2,4,5])