1

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?

2
  • 2
    create a loop that starts at your min value and ends on your max, and vice versa for descending Commented Apr 16, 2011 at 19:44
  • I'm not entirely sure what the properties of the series are supposed to be, but in any case, the descending parameter seems redundant, since the caller could simply provide a negative value for delta which would be equally intuitive. Also, mixing the two schemes for restraining into the range (modulo for the top range, clamp at the bottom range) seems odd too. Commented Apr 16, 2011 at 19:54

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.