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 C++

1 Answer

0 votes
#include <iostream>
#include <iomanip>
#include <sstream>
#include <unordered_set>
#include <vector>
#include <random>

/*
    Generate unique HEX colors using randomness.
    This produces different results each run, unlike deterministic HSL spacing.

    Approach:
    - Use std::random_device + std::mt19937 for strong randomness.
    - Generate random R, G, B values.
    - Convert to HEX (#RRGGBB).
    - Store in an unordered_set to avoid duplicates.
*/

// Convert an integer (0–255) to a two-digit HEX string.
std::string toHex(int value) {
    std::stringstream ss;
    ss << std::hex << std::setw(2) << std::setfill('0') << value;

    return ss.str();
}

// Generate N unique random HEX colors.
std::vector<std::string> generateRandomUniqueHexColors(std::size_t count) {
    std::unordered_set<std::string> seen;
    std::vector<std::string> colors;
    colors.reserve(count);

    std::random_device rd;          // non-deterministic seed
    std::mt19937 gen(rd());         // strong random engine
    std::uniform_int_distribution<> dist(0, 255);

    while (colors.size() < count) {
        int r = dist(gen);
        int g = dist(gen);
        int b = dist(gen);

        std::string hex = "#" + toHex(r) + toHex(g) + toHex(b);

        if (seen.insert(hex).second) {
            colors.push_back(hex);
        }
    }

    return colors;
}

int main() {
    std::size_t n = 12;

    auto colors = generateRandomUniqueHexColors(n);

    std::cout << "Generated HEX colors:\n";
    for (const auto& c : colors) {
        std::cout << c << "\n";
    }
}


/*
run:

Generated HEX colors:
#61a8b0
#ac6739
#a22d16
#dc87cd
#e41e92
#8d080c
#623b60
#061887
#1dd3e6
#183f89
#b04076
#167187

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz
...