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 Scala

1 Answer

0 votes
import scala.util.Random

object NonOverlappingRanges {

  def generateNonOverlappingRandomRanges(begin: Int, end: Int, numRanges: Int): List[(Int, Int)] = {
    val count = numRanges * 2

    // ------------------------------------------------------------
    // Generate unique random points in [begin, end)
    // The random numbers are chaotic and NOT sorted
    // ------------------------------------------------------------
    val rng = new Random()
    val pointsSet = Iterator
      .continually(begin + rng.nextInt(end - begin))
      .distinct                      // ensure uniqueness
      .take(count)                   // collect exactly count unique points
      .toList

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

    // ------------------------------------------------------------
    // Pair adjacent sorted points into (start, end) ranges
    // ------------------------------------------------------------
    sortedPoints
      .grouped(2)
      .collect { case List(a, b) => (a, b) }
      .toList
  }

  def main(args: Array[String]): Unit = {
    val start = 1
    val end = 500
    val numRanges = 8

    val ranges = generateNonOverlappingRandomRanges(start, end, numRanges)
    ranges.foreach { case (s, e) => println(s"($s, $e)") }
  }
}
 
 
 
 
/*
run:
 
(41, 46)
(47, 56)
(69, 93)
(112, 130)
(131, 154)
(233, 251)
(317, 386)
(392, 484)
 
*/

 



answered Jan 28 by avibootz

Related questions

...