How to generate a random color in RGB format with Scala

2 Answers

0 votes
import scala.util.Random

object RandomRGBColor {
  def generateRandomRGBColor(): Unit = {
    val red = Random.nextInt(256)
    val green = Random.nextInt(256)
    val blue = Random.nextInt(256)

    println(s"Random RGB Color: rgb($red, $green, $blue)")
  }

  def main(args: Array[String]): Unit = {
    generateRandomRGBColor()
  }
}



/*
run:

Random RGB Color: rgb(235, 11, 125)

*/

 



answered Oct 9, 2025 by avibootz
0 votes
/*
    Generate a random color in RGB format: rgb(R, G, B)
    This program demonstrates how numbers and bits are used
    to produce valid 8‑bit channel values.
*/

import scala.util.Random

object RandomRGBColor {

  /**
    * Create a random 8‑bit integer (0–255).
    * Random.nextInt(256) returns a value in [0, 256),
    * giving exactly one byte of color data.
    */
  def randomChannel(): Int = {
    // 8 bits → values from 0 to 255
    Random.nextInt(256)
  }

  /**
    * Produce a random RGB color by combining the channels.
    */
  def generateRandomRGB(): (Int, Int, Int, String) = {
    val r: Int = randomChannel() // Red channel (8 bits)
    val g: Int = randomChannel() // Green channel (8 bits)
    val b: Int = randomChannel() // Blue channel (8 bits)

    // Construct the CSS-style RGB string
    val rgb: String = s"rgb($r, $g, $b)"

    (r, g, b, rgb)
  }

  def main(args: Array[String]): Unit = {
    val (r, g, b, rgb) = generateRandomRGB()

    println(s"Red (8 bits): $r")
    println(s"Green (8 bits): $g")
    println(s"Blue (8 bits): $b")
    println(s"RGB color: $rgb")
  }
}


/*
run:

Red (8 bits): 88
Green (8 bits): 193
Blue (8 bits): 149
RGB color: rgb(88, 193, 149)

*/

 



answered Aug 23 by avibootz
...