/*
Generate a random color in HEX format (#RRGGBB).
This program demonstrates how numbers and bits are used
to produce a valid 24‑bit color value.
*/
import scala.util.Random
object RandomHexColor {
/**
* Create a 24‑bit random integer (0x000000–0xFFFFFF).
* Random.nextInt(n) returns a value in [0, n),
* so using 0x1000000 (2^24) gives exactly 24 bits.
*/
def randomColorInt(): Int = {
// 24 bits → values from 0 to 16,777,215 (0xFFFFFF)
Random.nextInt(0x1000000)
}
/**
* Convert a 24‑bit integer into a hex color string.
* "%06X" ensures exactly 6 uppercase hex digits.
*/
def intToHexColor(value: Int): String = {
f"#$value%06X"
}
/**
* Produce a random hex color by combining the two functions.
*/
def generateRandomHexColor(): (Int, String) = {
val value: Int = randomColorInt() // 24‑bit random number
val hex: String = intToHexColor(value) // Convert to #RRGGBB
(value, hex)
}
def main(args: Array[String]): Unit = {
val (value, hex) = generateRandomHexColor()
println(s"Random 24‑bit value: $value")
println(s"Hex color: $hex")
}
}
/*
run:
Random 24?bit value: 10554981
Hex color: #A10E65
*/