Reputation: 5
I am writing a javascript app and have 3 user selected numbers, Im stuck with a way of figuring out weather the numbers are all within plus and minus 5 of each other.
Upvotes: 0
Views: 106
Reputation: 6170
Wasn't sure if the difference between the lowest and the highest number had to be within 5, or if all numbers had to be. Since @Banana-In-Black had one solution covered, I went the other way:
This makes sure that there isn't more than 5 between each number (not just lowest and highest)
var withinFive = function(num1, num2, num3) {
var diff1 = Math.abs(num1 - num2);
var diff2 = Math.abs(num2 - num3);
return (diff1 <= 5 && diff2 <=5);
};
console.log(withinFive(1,2,7));
so in this example {1,2} is <= 5
and {2,7} <= 5
so the function returns true
Upvotes: 0
Reputation: 2557
function(num1, num2, num3) {
var array = [num1, num2, num3];
array.sort();
return Math.abs(array[0] - array[array.length - 1]) <= 5;
}
[Edit*] Another improved version if i misunderstand ur purpose:
function calculate() {
var array = new Array();
for(var i = 0; i < arguments.length; i++) {
// put every argument in a array
array.push(arguments[i]);
}
// sorting in ascending order
array.sort(function(a, b) { return a - b; });
var interval = array.length - 1;
// math part
return Math.abs(array[0] - array[interval]) <= interval * 5;
}
ex: calculate(4, 15, 7); // you'll get false
calculate(6, 10, 9, 16); // true
Upvotes: 2