首页 > 解决方案 > How to jump to 0 index of array if it will be exceeded in java?

问题描述

Let's say that i have an array of int's in range 65-90. I'll randomly pick one of elements and add 10 to it. Is it possible that value, if cross range of 90 return to 65? For example - i take a 85 and add 10 to it. So it should be 95, but i want a 70.

标签: javamathcalculation

解决方案


You can do it by placing your value in the interval [0, high - low] by removing low to your value, then add the number you want to it, take the modulo of the sum, and finally add low back to get back in the range [low, high]

public static void main(String[] args) {
    int low = 65, high = 90;
    System.out.println(addWithinInterval(85, 10, low, high));
}

private static int addWithinInterval(int value, int add, int low, int high) {
    return (value - low + add) % (high - low + 1) + low;
}

推荐阅读