This problem was recently asked by Google.
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.
function isAddedNumberInArray(inputAry, n) {
return (
inputAry
.map((el, index, ary) => {
//clone array
const clonedAry = ary.slice()
//remove the current element
clonedAry.splice(index, 1)
if (clonedAry.includes(n - el)) {
return true
} else {
return false
}
})
//if there is at least one true, then the whole thing is true
.some(el => el == true)
)
}
console.log(isAddedNumberInArray([10, 15, 3, 7], 17)) //true
console.log(isAddedNumberInArray([10, 15, 3, 7], 19)) //false
//check that the same number isn't used more than once
console.log(isAddedNumberInArray([10, 15, 3, 7], 14)) //false
//rearranged numbers
console.log(isAddedNumberInArray([15, 10, 3, 7], 17)) //true
console.log(isAddedNumberInArray([10, 15, 3, 7], 14)) //false
console.log(isAddedNumberInArray([9, 23, 1, 15, 3, 7], 22)) //true
Bonus: Can you do this in one pass?
//???