开发者

Java: Generate a sequence of numbers within a range?

I need to be able to generate a series of ascending or descending numbers within a range.

public int nextInRange(int last, int开发者_Python百科 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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜