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,844 questions

55,671 answers

573 users

How to generate a series of unique HEX colors in Scala

1 Answer

0 votes
import scala.util.Random

object HexColors {

  // Generates a single random color channel (0..255)
  def randomChannel(): Int = {
    // Random.nextInt(256) returns 0..255
    Random.nextInt(256)
  }

  // Builds a full random HEX color, e.g. "#a3f09c"
  def randomHexColor(): String = {
    val r: Int = randomChannel()
    val g: Int = randomChannel()
    val b: Int = randomChannel()

    // Format each channel as two-digit hex
    f"#$r%02x$g%02x$b%02x"
  }

  // Generates N unique random HEX colors
  def generateRandomUniqueHexColors(count: Int): List[String] = {
    // Use a mutable Set for uniqueness
    val colors = scala.collection.mutable.Set[String]()

    // Keep generating until we have the desired number
    while (colors.size < count) {
      colors += randomHexColor()
    }

    colors.toList
  }

  def main(args: Array[String]): Unit = {
    val n: Int = 12
    val colors: List[String] = generateRandomUniqueHexColors(n)

    println("Generated HEX colors:")
    colors.foreach(println)
  }
}


/*
run:

Generated HEX colors:
#b5add8
#e12bda
#a1d765
#875e93
#b10d0b
#ecfcd6
#437b16
#ac35fd
#45dfd6
#5a9cc0
#c822f6
#d2e5c2

*/

 



answered 5 hours ago by avibootz
...