Find the Smallest and Biggest Number (here)
Given an array, return an object with properties 'min', holding the smallest number in the array, and 'max', holding the largest number in the array.
function getExtremes(ary){
var x = {min:null,max:null}; // return null if ary length is 0
if(ary.length < 1) return x;
x.min = ary[0]; // default to first index of array
x.max = ary[0];
for(var xint = 1, len = ary.length;xint < len;xint++){
x.min = Math.min(x.min, ary[xint]);
x.max = Math.max(x.max, ary[xint]);
}
return x;
}
function test(){
var ary = [];
var len = Math.round(Math.random() * 10) + 1; // [1,11] inclusive
for(var xint = 0;xint < len;xint++)
ary.push(Math.round(Math.random() * 100)); // [0,100] inclusive
var polarz = getExtremes(ary);
console.log("Array " + ary.toString() + " has min: " + polarz.min + ", max: " + polarz.max);
}
test();
test();
test();
test();
test();
No comments:
Post a Comment