import Foundation
func generateNonOverlappingRandomRanges(
begin: Int,
end: Int,
numRanges: Int
) -> [(Int, Int)] {
let count = numRanges * 2
// ------------------------------------------------------------
// Generate unique random points in [begin, end)
// The random numbers are chaotic and NOT sorted
// ------------------------------------------------------------
var points = Set<Int>()
while points.count < count {
let r = Int.random(in: begin..<end)
points.insert(r) // Set ensures uniqueness
}
// ------------------------------------------------------------
// Sort the points
// Only AFTER sorting do the ranges become increasing
// and automatically non‑overlapping
// ------------------------------------------------------------
let sortedPoints = points.sorted()
// ------------------------------------------------------------
// Pair adjacent sorted points into (start, end) ranges
// ------------------------------------------------------------
var ranges: [(Int, Int)] = []
for i in stride(from: 0, to: sortedPoints.count, by: 2) {
ranges.append((sortedPoints[i], sortedPoints[i + 1]))
}
return ranges
}
let start = 1
let end = 500
let numRanges = 8
let ranges = generateNonOverlappingRandomRanges(begin: start, end: end, numRanges: numRanges)
for (s, e) in ranges {
print("(\(s), \(e))")
}
/*
run:
(76, 80)
(88, 164)
(179, 182)
(209, 248)
(273, 299)
(331, 335)
(351, 376)
(438, 456)
*/