function generateNonOverlappingRandomRanges(begin, end, numRanges) {
const count = numRanges * 2;
// ------------------------------------------------------------
// Generate unique random points in [begin, end)
// The random numbers are chaotic and NOT sorted
// ------------------------------------------------------------
const uniquePoints = new Set();
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 = [];
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:
[
[ 22, 38 ],
[ 52, 105 ],
[ 149, 172 ],
[ 177, 179 ],
[ 220, 235 ],
[ 240, 253 ],
[ 264, 359 ],
[ 428, 458 ]
]
*/