Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading