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 Kotlin

1 Answer

0 votes
import kotlin.random.Random

fun generateNonOverlappingRandomRanges(
    begin: Int,
    end: Int,
    numRanges: Int
): List<Pair<Int, Int>> {

    val count = numRanges * 2

    // ------------------------------------------------------------
    // Generate unique random points in [begin, end)
    // The random numbers are chaotic and NOT sorted
    // ------------------------------------------------------------
    val points = mutableSetOf<Int>()

    while (points.size < count) {
        val r = Random.nextInt(begin, end)
        points.add(r)   // Set ensures uniqueness
    }

    // ------------------------------------------------------------
    // Sort the points
    // Only AFTER sorting do the ranges become increasing
    // and automatically non‑overlapping
    // ------------------------------------------------------------
    val sortedPoints = points.toList().sorted()

    // ------------------------------------------------------------
    // Pair adjacent sorted points into (start, end) ranges
    // ------------------------------------------------------------
    return sortedPoints.chunked(2).map { (a, b) -> a to b }
}

fun main() {
    val start = 1
    val end = 500
    val numRanges = 8

    val ranges = generateNonOverlappingRandomRanges(start, end, numRanges)

    for ((s, e) in ranges) {
        println("($s, $e)")
    }
}




/*
run:

(13, 66)
(74, 81)
(82, 87)
(147, 154)
(158, 174)
(206, 215)
(234, 271)
(343, 344)

*/

 



answered Jan 28 by avibootz

Related questions

...