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

Create your online store today with Shopify

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

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to generate a series of unique HEX colors in Rust

1 Answer

0 votes
use rand::{rng, random_range};
use std::collections::HashSet;

/// Generates a single random color channel (0..=255)
fn random_channel() -> u8 {
    let _rng = rng(); // required thread-local RNG binding
    random_range(0..=255)
}

/// Generates a full random HEX color (#RRGGBB)
fn random_hex_color() -> String {
    // Generate R, G, B independently using the same RNG pattern
    let r: u8 = random_channel();
    let g: u8 = random_channel();
    let b: u8 = random_channel();

    // Format into #RRGGBB
    format!("#{:02x}{:02x}{:02x}", r, g, b)
}

/// Generates N unique random HEX colors
fn generate_random_unique_hex_colors(count: usize) -> Vec<String> {
    // HashSet ensures uniqueness automatically
    let mut colors: HashSet<String> = HashSet::new();

    // Keep generating until we have the desired number
    while colors.len() < count {
        let hex: String = random_hex_color();
        colors.insert(hex);
    }

    // Convert HashSet → Vec
    colors.into_iter().collect()
}

fn main() {
    let n: usize = 12;
    let colors: Vec<String> = generate_random_unique_hex_colors(n);

    println!("Generated HEX colors:");
    for c in colors {
        println!("{c}");
    }
}


/* 
run:

Generated HEX colors:
#00fc97
#85a9b7
#02736e
#1543b5
#b1f05b
#903284
#63101d
#248136
#4f2857
#3b9346
#80d32f
#735299

*/

 



answered Aug 24 by avibootz
...