Tuesday, September 27, 2016

a/A Practice Problems: Two Sum

It's been a minute. A New York minute, if you will. Cheeeese.  Today we're back with another App Academy practice problem.  Here it is:

# Write a method that takes an array of numbers. If a pair of numbers
# in the array sums to zero, return the positions of those two numbers.
# If no pair of numbers sums to zero, return `nil`.

A couple things beforehand: nil in javascript would be null, so I return null. I came to a working answer through trial and error, but I'm pretty sure there is a much better way to solve this. I tried a couple other ways, but nothing worked so any advice out there would be more than welcome!!


I started the first loop off at 0 and the second loop at 1 because there's no need to add the first index to itself.  Just remember the way nested loops work : the second loop will finish an entire iteration (from 1 to less than nums.length before the first loop moves on to i = 1.

That last line there was my test case, so don't mind that! :) Usually when I solve problems, I write everything out. I'm working on being more concise with my code, which is why I didn't declare an array and then push the values to it (even though I definitely tried this a billion times). But I gotta say, I kinda liked just returning i and j in an array.

That's all for today.
Happy coding! :)

No comments :

Post a Comment