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 Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math/rand"
    "sort"
    "time"
)

// generateNonOverlappingRandomRangescreates numRanges random (start,end) pairs
// that are guaranteed to be non-overlapping.
//
// 1. Generate unique random points (chaotic order)
// 2. Sort them
// 3. Pair adjacent points → automatically non-overlapping
func generateNonOverlappingRandomRanges(begin, end, numRanges int) [][2]int {
    count := numRanges * 2

    rand.Seed(time.Now().UnixNano())

    // ------------------------------------------------------------
    // Generate unique random points in [begin, end)
    // The random numbers are chaotic and NOT sorted
    // ------------------------------------------------------------
    pointsSet := make(map[int]struct{})

    for len(pointsSet) < count {
        r := begin + rand.Intn(end-begin)
        pointsSet[r] = struct{}{}
    }

    // Convert map keys → slice
    points := make([]int, 0, count)
    for p := range pointsSet {
        points = append(points, p)
    }

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

    // ------------------------------------------------------------
    // Pair adjacent sorted points into (start, end) ranges
    // ------------------------------------------------------------
    ranges := make([][2]int, 0, numRanges)
    for i := 0; i < len(points); i += 2 {
        ranges = append(ranges, [2]int{points[i], points[i + 1]})
    }

    return ranges
}

func main() {
    start := 1
    end := 500
    numRanges := 8

    ranges := generateNonOverlappingRandomRanges(start, end, numRanges)

    for _, r := range ranges {
        fmt.Printf("(%d, %d)\n", r[0], r[1])
    }
}



/*
run:

(71, 75)
(92, 97)
(101, 144)
(145, 203)
(240, 288)
(345, 402)
(406, 440)
(447, 481)

*/

 



answered Jan 28 by avibootz
edited Jan 28 by avibootz

Related questions

...