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

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>

std::vector<std::pair<int,int>> generate_non_overlapping_random_ranges(
        int begin, int end, int num_ranges)
{
    int count = num_ranges * 2;
    std::vector<int> points;
    points.reserve(count);

    // Random engine
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dist(begin, end - 1);

    // Generate unique random points, the random numbers is chaotic
    while (points.size() < count) {
        int x = dist(gen);
        if (std::find(points.begin(), points.end(), x) == points.end())
            points.push_back(x);
    }

    // The ranges increase and become non‑overlapping only after sorting
    std::sort(points.begin(), points.end());

    // Once sorted, we pair them 
    std::vector<std::pair<int,int>> ranges;
    ranges.reserve(num_ranges);

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

    return ranges;
}

int main() {
    int start = 1;
    int end = 500;
    int num_ranges = 8;

    auto ranges = generate_non_overlapping_random_ranges(start, end, num_ranges);

    for (auto &r : ranges) {
        std::cout << "(" << r.first << ", " << r.second << ")\n";
    }
}



/*
run:

(4, 54)
(71, 106)
(145, 170)
(178, 197)
(260, 299)
(315, 319)
(345, 403)
(442, 457)

*/

 



answered Jan 27 by avibootz
edited Jan 28 by avibootz

Related questions

...