Created
May 17, 2018 16:49
-
-
Save mecampbellsoup/4d1ef8481e2293da4a80d1d4b0d471e2 to your computer and use it in GitHub Desktop.
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
require 'rspec/autorun' | |
require 'pry' | |
def two_sum(nums, target) | |
# for each integer in the input list | |
# calculate the sum with every other member | |
nums.each_with_index do |outer_n, outer_index| | |
nums.detect.with_index do |inner_n, inner_index| | |
next if inner_index == outer_index | |
return [outer_index, inner_index] if outer_n + inner_n == target | |
end | |
end | |
end | |
RSpec.describe "two_sum" do | |
it 'returns the indexes of the two numbers which sum to the target' do | |
nums = [2, 7, 11, 15] | |
target = 9 | |
expect(two_sum(nums, target)).to eq [0, 1] | |
end | |
it 'does not use an element twice' do | |
nums = [3, 2, 4] | |
target = 6 | |
expect(two_sum(nums, target)).to eq [1, 2] | |
end | |
it 'works with negative numbers' do | |
nums = [3, 0, 0, 4, -3] | |
target = 0 | |
expect(two_sum(nums, target)).to eq [0, 4] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment