DAY 9
0

## Two Sum 演算法初階題，Ruby 30 天刷題修行篇第九話

Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2).

For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.

The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).

``````twoSum [1, 2, 3] 4 === (0, 2)
``````

``````def two_sum(numbers, target)
i = 0
j = 1
arr = []

while i < numbers.length
while j < numbers.length
if numbers[i] + numbers[j] == target
arr << i
arr << j
break
end
j += 1
end
i += 1
j = i + 1
end
arr
end
``````

``````def twoSum(numbers, target)
numbers.each_with_index do |n1, i1|
numbers.each_with_index do |n2, i2|
return [i1, i2] if (n1 + n2) == target && i1 != i2
end
end
end
``````