Created
June 12, 2018 21:41
-
-
Save thomasvaeth/b8d430949aa51c6fe52cd5e0ee93db17 to your computer and use it in GitHub Desktop.
"In the midst of chaos, there is also opportunity." - Sun Tzu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function closestProduct(arr, num) { | |
const result = []; | |
let total = 0; | |
let difference = Infinity; | |
for (let i = 0; i < arr.length; i++) { | |
for (let j = i + 1; j < arr.length; j++) { | |
total = arr[i] * arr[j]; | |
if (Math.abs(total - num) < difference) { | |
difference = Math.abs(total - num); | |
result.length = 0; | |
result.push(arr[i], arr[j]); | |
} | |
} | |
} | |
return result; | |
} | |
closestProduct([5,3,8,2,7], 42); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment