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
...