Two-Sum
- Define a method,
two_sum
, that accepts an array and a target sum (integer) as arguments. - The method should return true if any two integers in the array sum to the target.
- Otherwise, it should return false. Assume the array will only contain integers.
def two_sum(array, target)
i = 0
sum = []
while i < array.max
i = i + 1
b = i + i
sum.push(b)
end
sum.include?(target)
end
puts "------Two Sum------"
puts two_sum([1,2,3,4,5,6], 8) == true #(im getting true)
puts two_sum([1,2,3,4,5,6], 18) == false #(im getting true)
puts two_sum([1,3,6], 6) == false #(im getting false)
puts two_sum([1,8,2,1], 0) == false #(im getting true)
You loop through each element of the array, which is a good start. Inside this loop, you need to try adding together each pair of elements. At the moment, all you're pushing to your sum array is
i+i
: the index doubled (i.e. every even number from 0 to double the largest element of your array).You could attempt to sum each pair of elements by having two loops, one inside the other. They'd both iterate through the elements of the array. In your inner loop, you'd attempt to add the current element from the outer loop to the current element from the inner loop. If you get any matches, you can return true and quit immediately; otherwise return false.
The ruby solution looks like:
Array#combination
returns all the combinations of two elements andEnumerable#any?
returnstrue
if the block evaluates totrue
andfalse
otherwise.This is an attempt to speed the calculations when performance is important, particularly when the array is large and contains many duplicate values.
Code
Examples
Explanation
The code for even values of
target
serves two purposes:target
, and that value appears at least twice in the array; andtrue
, it permits the removal of duplicate values inarr
before the remaining calculations are performed.For the first example the steps are as follows.
so
true
is not returned.The first element of
b
is now passed to the block.The next steps are as follows.
so
true
is returned.