Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,003 questions

51,950 answers

573 users

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

1 Answer

0 votes
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]] 
 
*/

 



answered Jan 28 by avibootz
edited Jan 28 by avibootz

Related questions

...