function generateNonOverlappingRandomRanges(
begin: number,
end: number,
numRanges: number
): Array<[number, number]> {
const count = numRanges * 2;
// ------------------------------------------------------------
// Generate unique random points in [begin, end)
// The random numbers are chaotic and NOT sorted
// ------------------------------------------------------------
const uniquePoints = new Set<number>();
while (uniquePoints.size < count) {
const r = begin + Math.floor(Math.random() * (end - begin));
uniquePoints.add(r); // Set ensures uniqueness
}
// Convert Set → Array so we can sort
const points = Array.from(uniquePoints);
// ------------------------------------------------------------
// Sort the points
// Only AFTER sorting do the ranges become increasing
// and automatically non‑overlapping
// ------------------------------------------------------------
points.sort((a, b) => a - b);
// ------------------------------------------------------------
// Pair adjacent sorted points into (start, end) ranges
// ------------------------------------------------------------
const ranges: Array<[number, number]> = [];
for (let i = 0; i < points.length; i += 2) {
ranges.push([points[i], points[i + 1]]);
}
return ranges;
}
const start = 1;
const end = 500;
const numRanges = 8;
console.log(generateNonOverlappingRandomRanges(start, end, numRanges));
/*
run:
[[13, 76], [109, 119], [157, 158], [183, 195], [227, 255], [296, 350], [358, 405], [438, 496]]
*/