Given a number x and a range n. Generate ranges of size n from x

Suppose x = 99, n = 20
Output should be : 0-19, 20-39, 40-59, 60-79, 80 – 98

Suppose x = 5, n = 20
Output should be : 0 – 4

Suppose x = 0, n = 20
Output: No possible range

I’m looking for any inbuilt java implementation for the above

I tried implementing the above but would prefer a library method if possible.

>Solution :

I would just use a simple for loop:

public static void main(String[] args) {
    System.out.println(ranges(99, 20));
    System.out.println(ranges(5, 20));
    System.out.println(ranges(0, 20));
}

static List<List<Integer>> ranges(int x, int n){
    List<List<Integer>> ranges = new ArrayList<>();
    for (int i = 0; i < x; i += n){
        ranges.add(List.of(i, Math.min(i + n - 1, x-1)));
    }
    return ranges;
}

output:

[[0, 19], [20, 39], [40, 59], [60, 79], [80, 98]]
[[0, 4]]
[]

Instead of returning an empty list in the last case, you could also throw an exception

Leave a Reply