javascript number counting
I am slightly stuck on the javascript logic to accomplish this.
Basically
If I give a number (say 30)
I want to show 5 either side.
so
25 26 27 28 29 30 31 32 33 34 35
That part is easy.
But then I need to handle cases where the number is below 5 (say 3).
What I want to to is,
for every number not shown on the right, add it to the left
so
1 2 3 4 5 6 7 8 9 10 11
But then I need to handle cases wher开发者_如何学Goe the number is above a (maximum-5) (say maximum = 100, number = 98).
What I want to to is,
for every number not shown on the left, add it to the right
so
90 91 92 93 94 95 96 97 98 99 100
But then I need to handle cases where the maximum is below 10 (say number = 3, maximum = 8
What I want to to is,
only show the applicable range
so
1 2 3 4 5 6 7 8
But I am not sure on the logic
function ranger(num) {
//Establish limits and pre/post array storage
var low = 0, high = 100, howMany = 5;
var pre = [];
var post = [];
//Increment/decrement if appropriate
for(x=1;x<=howMany;x++) {
if((num-x) > low) { pre.push(num-x); }
if((num+x) < high) { post.push(num+x); }
}
pre.reverse();
alert("Before: "+pre+'\nNumber: '+num+'\nAfter: '+post)
}
ranger(7);
ranger(2);
ranger(96);
Tested for all your cases:
range = 5;
maximum = 8;
number = 3;
left = right = number;
while(right - left < range*2 ) {
if (right + 1 <= maximum) {
right++;
}
if (left - 1 > 0 ) {
left--;
}
if (right == maximum && left == 1) {
break;
}
}
for(i=left;i<=right;i++) {
console.log(i);
}
One possible solution:
function getPages(fromPageNumber) {
var result = [];
fromPageNumber= Math.min(94, Math.max(6, fromPageNumber));
for(var i = -5; i <=5; i++)
result.push(fromPageNumber + i);
return result;
}
// Set up your limits and bounds
var radius = 5.
middleNumber = 20,
lowerBound = 1,
upperBound = 100;
// For the defined (and available range) create an array of valid numbers
var results = [];
for (int i = Math.max(middleNumber - radius, lowerBound);
i <= Math.min(middleNumber + radius, upperBound);
i++) {
results.push(i);
}
// Print out the resulting numbers with spaces in between
console.log(results.join(' '));
function getSequence(num, length)
{
var min = 0;
var max=100;
Array result;
for(int i=num-(length/2); i<num+(length/2);i++)
{
if(i>min && i< max)
result.add(i);
}
return result;
}
精彩评论