#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
*/