How to generate non‑overlapping random ranges (start,end),(start,end) in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class NonOverlappingRanges {

    public static List<int[]> generateNonOverlappingRandomRanges(int begin, int end, int numRanges) {
        int count = numRanges * 2;
        Random rand = new Random();

        // We use a Set to ensure the uniqueness of random points
        Set<Integer> uniquePoints = new HashSet<>();

        // ------------------------------------------------------------
        // Generate unique random points in [begin, end)
        // The random numbers are chaotic and NOT sorted
        // ------------------------------------------------------------
        while (uniquePoints.size() < count) {
            int r = begin + rand.nextInt(end - begin);
            uniquePoints.add(r);
        }

        // Move them into a list so we can sort
        List<Integer> points = new ArrayList<>(uniquePoints);

        // ------------------------------------------------------------
        // Sort the points
        // Only AFTER sorting do the ranges become increasing
        // and automatically non‑overlapping
        // ------------------------------------------------------------
        Collections.sort(points);

        // ------------------------------------------------------------
        // Pair adjacent sorted points into (start, end) ranges
        // ------------------------------------------------------------
        List<int[]> ranges = new ArrayList<>();
        for (int i = 0; i < points.size(); i += 2) {
            ranges.add(new int[]{points.get(i), points.get(i + 1)});
        }

        return ranges;
    }

    public static void main(String[] args) {
        int start = 1;
        int end = 500;
        int numRanges = 8;

        List<int[]> ranges = generateNonOverlappingRandomRanges(start, end, numRanges);

        for (int[] r : ranges) {
            System.out.println("(" + r[0] + ", " + r[1] + ")");
        }
    }
}



/*
run:

(121, 447)
(488, 489)

*/

 



answered Jan 27 by avibootz
edited Jan 28 by avibootz

Related questions

...