Skip to content
loading...

re: Daily Challenge #141 - Two Sum VIEW POST

FULL DISCUSSION
 

Simple Ruby method chain:

def two_sum(a, target)
  a
    .each_with_index
    .to_a
    .combination(2)
    .inject([]) { |r, ((a, i1), (b, i2))| r << [i1, i2] if a + b == target ; r }
end

two_sum([1234,5678,9012], 14690) 
#=> [[1, 2]]

two_sum([5,10,15,20,25,30], 50)
#=> [[3,5]]

Note: it's generally preferable to use each_with_object instead of inject + explicitly returning r in the block, but this is just a coding challenge and it made the line fit within 80 characters πŸ˜‰

 
Sloan, the sloth mascot Comment marked as low quality/non-constructive by the community View code of conduct

Ruby 😍
This one is ugly tho

 

You’re more than welcome to provide an alternative.

code of conduct - report abuse