Search code examples
javaclamp

I am trying to create a Clamp method in java


Hey so I am trying to code a random delay using a minimum ms delay, maximum ms delay and some other calculations. For this I need to clamp some integers and a long. Below is a class that I called MathUtil to try to code a Clamp.

public static long clamp(long delayPreClamp, int min, int max) {
    return 90;
}

The numbers it is using you can find below:

double deviation = 22;
                    double mean = 90;
                    int min = 43;
                    int max = 198;
                    Random r = new Random();
                    double randGauss = (r.nextGaussian() * deviation);
                    long delayPreClamp = Math.round(randGauss + mean);
                    long delay = (long) MathUtil.clamp(delayPreClamp, min, max);

My issue is that in the first mentioned code, I can only return min, max, delayPreClamp or a number. I need it to create a new number that will be the delay.


Solution

  • Clamp

    public static long clamp(long delayPreClamp, int min, int max) {
        // v = delayPreClamp
        // if v < min, returns the greater between min and v, thus min
        // if v > max, returns the greater between min and max, thus max
        // if v is between min and max, returns the greater between min and v, thus v
        return Math.max(min, Math.min(delayPreclamp, max));
    }