Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active January 23, 2017 00:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save primaryobjects/8ece24eb1a3fc37338f2fdf95c8c1f78 to your computer and use it in GitHub Desktop.
Find a product within an array of numbers. Demo at http://jsbin.com/zidogenaro/edit?js,console
var mathManager = {
findProduct: function(product, arr) {
var result = null;
for (var i=0; i<arr.length; i++) {
for (var j=i+1; j<arr.length; j++) {
if (product === arr[i] * arr[j]) {
result = [arr[i], arr[j]];
break;
}
}
if (result) {
break;
}
}
return result;
}
};
var arr = [1, 3, 6, 8, 9, 2, 0, 11, 7];
var result = mathManager.findProduct(18, arr);
console.log('Find product 18 in ' + arr);
console.log(result);
console.log(result.length===2 && result.every(function(v,i) { return v === [3,6][i]; }));
result = mathManager.findProduct(19, arr);
console.log('Find product 19 in ' + arr);
console.log(result);
console.log(result === null);
var result = mathManager.findProduct(22, arr);
console.log('Find product 22 in ' + arr);
console.log(result);
console.log(result.length===2 && result.every(function(v,i) { return v === [2,11][i]; }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment