Menu

It’s Day 1 of the Daily Coding Problem. So here it is:

Given a list of numbers and a number`k`

, return whether any two numbers from the list add up to`k`

.

For example, given `[10, 15, 3, 7]`

and `k`

of `17`

, return true since `10 + 7`

is `17`

.

Bonus: Can you do this in one pass?

As a Mental Exercise… here’s what I’d to do approach this:

First… I’d create an array of numbers and let it remain static.

[4, 6, 13, 8, 17, 3, 9] .. I could add more numbers, but lets keep it simple with numbers under 20.

Then I’d pick a value for K that I KNOW would work.. like 20. because two of my numbers 17 and 3 will add to 20.

Second… I’d create a nested FOR-LOOP that indexes through the array and picks the first number and holds onto it in a variable x. The inner loop with go through the remaining numbers and place one at a time into variable y. It will then check to add x+y and see if it equals k. IF it does… print out x+y=k to the screen.

After it checks.. the inner loop goes to the next number until there are no more numbers left.

It would go like this:

4 + 6 = 10… 10 does not equal 20 so nothing happens…

4 + 13 = 17… 17 does not equal 20 so nothing happens…

… and so on.

After trying to add 4 to all the other numbers… the outer loop moves on to the next number 6.

6 + 13 = 19…. 19 does not equal 20 so nothing happens…

6 + 8 = 14…. 14 does not equal 20 so nothing happens…

Notice that I did not add 6 to the first array number 4. We already checked 4 + 6 so there’s no reason to check 6 + 4 now.

Eventually… the Outer loop will grab 17 for variable X and the inner loop will grab 3 for y. and we will print 17 + 3 = 20. x+y=k.

So that’s my plan. I don’t know if this is the “right” answer, but it’s what I’ve got.