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.

39,762 questions

51,662 answers

573 users

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

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static List<(int Start, int End)> generateNonOverlappingRandomRanges(int begin, int end, int numRanges)
    {
        int count = numRanges * 2;
        Random rnd = new Random();

        // ------------------------------------------------------------
        // Generate unique random points in [begin, end)
        // The random numbers are chaotic and NOT sorted
        // ------------------------------------------------------------
        HashSet<int> uniquePoints = new HashSet<int>();

        while (uniquePoints.Count < count) {
            int r = begin + rnd.Next(end - begin);
            uniquePoints.Add(r);   // HashSet ensures uniqueness
        }

        // Move to a list so we can sort
        List<int> points = new List<int>(uniquePoints);

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

        // ------------------------------------------------------------
        // Pair adjacent sorted points into (start, end) ranges
        // ------------------------------------------------------------
        List<(int Start, int End)> ranges = new List<(int, int)>();

        for (int i = 0; i < points.Count; i += 2) {
            ranges.Add((points[i], points[i + 1]));
        }

        return ranges;
    }

    static void Main()
    {
        int start = 1;
        int end = 500;
        int numRanges = 8;

        var ranges = generateNonOverlappingRandomRanges(start, end, numRanges);

        foreach (var r in ranges) {
            Console.WriteLine($"({r.Start}, {r.End})");
        }
    }
}



/*
run:

(19, 97)
(164, 207)
(236, 296)
(305, 358)
(368, 370)
(405, 431)
(440, 446)
(458, 485)

*/

 



answered 3 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...