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 <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

/*
    Generate unique HEX colors using randomness in C.

    Notes:
    - Uses rand() seeded with time(NULL) for different results each run.
    - Ensures uniqueness by storing generated colors in an array and
      checking for duplicates.
    - Produces #RRGGBB strings.
*/

// Convert an integer (0–255) to a two-digit HEX string.
void to_hex(int value, char *out) {
    sprintf(out, "%02x", value);
}

// Check if a HEX color already exists in the array.
int exists(const char colors[][8], size_t count, const char *hex) {
    for (size_t i = 0; i < count; i++) {
        if (strcmp(colors[i], hex) == 0) {
            return 1;
        }
    }
    
    return 0;
}

// Generate N unique random HEX colors.
void generate_random_unique_hex_colors(char (*colors)[8], size_t count) {
    size_t generated = 0;

    while (generated < count) {
        int r = rand() % 256;
        int g = rand() % 256;
        int b = rand() % 256;

        char hex[8];
        char rr[3], gg[3], bb[3];

        to_hex(r, rr);
        to_hex(g, gg);
        to_hex(b, bb);

        sprintf(hex, "#%s%s%s", rr, gg, bb);

        if (!exists(colors, generated, hex)) {
            strcpy(colors[generated], hex);
            generated++;
        }
    }
}

int main(void) {
    size_t n = 12;
    char colors[12][8];

    srand((unsigned)time(NULL));  // different results each run

    generate_random_unique_hex_colors(colors, n);

    printf("Generated HEX colors:\n");
    for (size_t i = 0; i < n; i++) {
        printf("%s\n", colors[i]);
    }

    return 0;
}



/*
run:

Generated HEX colors:
#852737
#64b3e2
#83aa47
#25cd97
#ed9d80
#320ac6
#b350cc
#cda890
#341105
#9e4eae
#d6d3d5
#0d3888

*/

 



answered 1 day ago by avibootz
...