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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to generate N random integers, each with distinct digits and exact length L in Scala

1 Answer

0 votes
import scala.util.Random

object DistinctDigitGenerator {

  // Generate N random integers, each with distinct digits and exact length L
  def generateNumbers(n: Int, length: Int): List[Int] = {

    // Helper: checks if all digits in the number are distinct
    def hasDistinctDigits(num: Int): Boolean = {
      val digits = num.toString
      digits.distinct.length == digits.length
    }

    // Lower and upper bounds for numbers with exactly L digits
    val lower = math.pow(10, length - 1).toInt
    val upper = math.pow(10, length).toInt - 1

    // Keep generating until we collect N valid numbers
    def loop(acc: List[Int]): List[Int] = {
      if (acc.length >= n) acc
      else {
        val candidate = Random.between(lower, upper + 1)
        if (hasDistinctDigits(candidate))
          loop(candidate :: acc)
        else
          loop(acc)
      }
    }

    loop(Nil)
  }

  def main(args: Array[String]): Unit = {
    val result = generateNumbers(10, 6) 
    println(result)
  }
}



/*
run:

List(463908, 340621, 980126, 735109, 497250, 617320, 362879, 938206, 967421, 281945)

*/

 



answered Jul 16 by avibootz

Related questions

...