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

1 Answer

0 votes
function generate_non_overlapping_random_ranges(int $begin, int $end, int $numRanges): array
{
    $count = $numRanges * 2;

    // ------------------------------------------------------------
    // Generate unique random points in [begin, end)
    // The random numbers are chaotic and NOT sorted
    // ------------------------------------------------------------
    $points = [];

    while (count($points) < $count) {
        $r = rand($begin, $end - 1);
        $points[$r] = true;   // using keys ensures uniqueness
    }

    // Convert keys back to a normal array
    $points = array_keys($points);

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

    // ------------------------------------------------------------
    // Pair adjacent sorted points into (start, end) ranges
    // ------------------------------------------------------------
    $ranges = [];

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

    return $ranges;
}

$start = 1;
$end = 500;
$numRanges = 8;

$ranges = generate_non_overlapping_random_ranges($start, $end, $numRanges);

print_r($ranges);



/*
run:

Array
(
    [0] => Array
        (
            [0] => 38
            [1] => 51
        )

    [1] => Array
        (
            [0] => 67
            [1] => 80
        )

    [2] => Array
        (
            [0] => 138
            [1] => 179
        )

    [3] => Array
        (
            [0] => 193
            [1] => 265
        )

    [4] => Array
        (
            [0] => 307
            [1] => 326
        )

    [5] => Array
        (
            [0] => 339
            [1] => 355
        )

    [6] => Array
        (
            [0] => 418
            [1] => 472
        )

    [7] => Array
        (
            [0] => 479
            [1] => 480
        )

)

*/

 



answered Jan 28 by avibootz
edited Jan 29 by avibootz

Related questions

...