How to generate 3 no-digit repeated random integers, each with distinct digits in Scala

1 Answer

0 votes
import scala.util.Random

object DistinctDigitGenerator {

  // ------------------------------------------------------------
  // Function: generate_number
  // Purpose: Create one 3-digit integer with distinct digits,
  //          drawn from a shared pool of available digits.
  //          The first digit is never zero, so the result
  //          is always a true 3-digit integer.
  // ------------------------------------------------------------
  def generate_number(available_digits: scala.collection.mutable.ListBuffer[String],
                      length: Int = 3): Int = {

    // Choose the first digit from the pool, excluding '0'
    val non_zero_digits = available_digits.filter(_ != "0")
    val first_digit = non_zero_digits(Random.nextInt(non_zero_digits.size))
    available_digits -= first_digit

    // Choose the remaining digits from the updated pool
    val remaining = scala.collection.mutable.ListBuffer[String]()
    for (_ <- 1 until length) {
      val d = available_digits(Random.nextInt(available_digits.size))
      remaining += d
      available_digits -= d
    }

    // Build the number as a string, then convert to int
    val digits_str = first_digit + remaining.mkString("")
    digits_str.toInt
  }


  // ------------------------------------------------------------
  // Function: generate_three_distinct_digit_numbers
  // Purpose: Produce three integers, each with distinct digits,
  //          and no digit repeated across all three numbers.
  //          All numbers are guaranteed to be 3 digits long.
  // ------------------------------------------------------------
  def generate_three_distinct_digit_numbers(): (Int, Int, Int) = {

    // Start with all digits 0–9 as strings
    val digits = scala.collection.mutable.ListBuffer[String]()
    for (i <- 0 to 9) digits += i.toString

    // Generate three numbers, each 3 digits long
    val n1 = generate_number(digits)
    val n2 = generate_number(digits)
    val n3 = generate_number(digits)

    (n1, n2, n3)
  }


  // ------------------------------------------------------------
  // Main execution
  // ------------------------------------------------------------
  def main(args: Array[String]): Unit = {

    // Run the generator 5 times
    for (_ <- 1 to 5) {
      val (n1, n2, n3) = generate_three_distinct_digit_numbers()
      println(s"($n1, $n2, $n3)")
    }
  }
}



/*
run:

(172, 608, 935)
(193, 256, 407)
(250, 897, 413)
(693, 420, 751)
(954, 608, 231)

*/

 



answered 11 hours ago by avibootz

Related questions

...