I need to be able to generate a series of ascending or descending numbers within a range.
public int nextInRange(int last, int min, int max, int delta, boolean descending) {
delta *= descending ? -1 : 1;
int result = last + delta;
result %= max;
return Math.max(result, min);
}
This works fine for ascending values, but not descending values. I've been staring at this for a while, and I'm not sure how to make it work for descending values. Any ideas?
How about this, where delta
is negative when you want a descending sequence?
public int nextInRange(int last, int min, int max, int delta) {
int result = last + delta;
// now clip to min and max
if (result > max) {
result = max;
} else if (result < min) {
result = min;
}
return result;
}
or perhaps less straightforwardly, have the body of the function be the single line:
return Math.min(max, Math.max(last + delta, min));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.