Skip to content

Instantly share code, notes, and snippets.

@thomasvaeth
Created June 12, 2018 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasvaeth/b8d430949aa51c6fe52cd5e0ee93db17 to your computer and use it in GitHub Desktop.
Save thomasvaeth/b8d430949aa51c6fe52cd5e0ee93db17 to your computer and use it in GitHub Desktop.
"In the midst of chaos, there is also opportunity." - Sun Tzu
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