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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,569 questions

56,787 answers

573 users

How to generate N unique random numbers between min and max in Scala

1 Answer

0 votes
import scala.util.Random

def generateUniqueRandomNumbers(N: Int, min: Int, max: Int): Vector[Int] = {
  require(max - min + 1 >= N, "Range is too small to generate the desired number of unique random numbers")
  
  val random = new Random()
  var numbers = Set.empty[Int]
  
  while (numbers.size < N) {
    numbers += random.nextInt((max - min) + 1) + min
  }
  
  numbers.toVector
}

val N = 8

val uniqueNumbers = generateUniqueRandomNumbers(N, 1, 20)

println(uniqueNumbers)



/*
run:

Vector(14, 20, 1, 13, 2, 7, 3, 18)

*/

 



answered Sep 25, 2024 by avibootz

Related questions

1 answer 200 views
1 answer 230 views
1 answer 215 views
1 answer 213 views
2 answers 284 views
...