Skip to content

Instantly share code, notes, and snippets.

@jsonzilla
Created August 29, 2023 12:56
Show Gist options
  • Save jsonzilla/6263aa482a9f41e7a33a817b342e9630 to your computer and use it in GitHub Desktop.
Save jsonzilla/6263aa482a9f41e7a33a817b342e9630 to your computer and use it in GitHub Desktop.
Color generator
#include <iostream>
#include <vector>
#include <random>
#include <algorithm>
#include <cmath>
struct Color {
int r, g, b;
Color(int r, int g, int b) : r(r), g(g), b(b) {}
double luminance() const {
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
double contrast(const Color& other) const {
double l1 = luminance();
double l2 = other.luminance();
return (std::max(l1, l2) + 0.05) / (std::min(l1, l2) + 0.05);
}
};
std::vector<Color> generate_palette(int num_colors, double min_contrast) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dist(0, 255);
std::vector<Color> palette;
palette.emplace_back(dist(gen), dist(gen), dist(gen));
while (palette.size() < num_colors) {
Color new_color(dist(gen), dist(gen), dist(gen));
bool valid = true;
for (const Color& color : palette) {
if (new_color.contrast(color) < min_contrast) {
valid = false;
break;
}
}
if (valid) {
palette.push_back(new_color);
}
}
return palette;
}
int main() {
std::vector<Color> palette = generate_palette(5, 4.5);
for (const Color& color : palette) {
std::cout << "RGB(" << color.r << ", " << color.g << ", " << color.b << ")" << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment