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 Kotlin

1 Answer

0 votes
import kotlin.random.Random

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

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

    // Format each channel as two-digit hex
    return "#%02x%02x%02x".format(r, g, b)
}

// Generates N unique random HEX colors
fun generateRandomUniqueHexColors(count: Int): List<String> {
    // MutableSet ensures uniqueness automatically
    val colors: MutableSet<String> = mutableSetOf()

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

    // Convert to a List (immutable)
    return colors.toList()
}

fun main() {
    val n: Int = 12
    val colors: List<String> = generateRandomUniqueHexColors(n)

    println("Generated HEX colors:")
    colors.forEach { println(it) }
}


/*
run:

Generated HEX colors:
#c75625
#878de6
#039b07
#7d06e7
#d4797e
#7beed9
#f22126
#796922
#99ca11
#7a537e
#4e1fe5
#35e759

*/

 



answered 5 hours ago by avibootz
...