Daily Coding: Day One

I recently signed up for this website in a continued effort to keep my skills sharp but to also have something fun to do. I don’t know that I will always do it, or always post my solution, but I will endeavor for both. It’s a pickle!

1
2
3
4
5
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?

And here is my crack at it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function findNumbers(listOfNumbers, k) {
let result = false

for (const n of listOfNumbers) {
let x = k > n ? k - n : n - k
let y = k > x ? k - x : x - k

console.log("First No: " + x + " Second No: " + y)

if (listOfNumbers.includes(x)
&& listOfNumbers.includes(y)) {
if (x === y) {
if (listOfNumbers.filter(f => f === x).length > 1) {
result = true
break
}
}
else {
result = true
break
}
}
}

console.log("Result is:" + result);
}

findNumbers([1, 2, 3], 6)
findNumbers([1, 15, 3, 9, 12, 7, 10], 17)
findNumbers([9, 15, 3, 7, 8, 22, 100, 46, 11, 0, 10, 1], 11)

Output of this is

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/usr/local/bin/node ./dayOne.js
First No: 5 Second No: 1
First No: 4 Second No: 2
First No: 3 Second No: 3
Result is:false
First No: 16 Second No: 1
First No: 2 Second No: 15
First No: 14 Second No: 3
First No: 8 Second No: 9
First No: 5 Second No: 12
First No: 10 Second No: 7
Result is:true
First No: 2 Second No: 9
First No: 4 Second No: 7
First No: 8 Second No: 3
Result is:true

Fun! A usable version is here via JSFiddle but overall this is a pretty simple solution which I could probably optimize beyond the fifteen minutes I took to get it but it works and the mantra is always make it work, make it good, make it fast