Skip to content

Instantly share code, notes, and snippets.

@wchargin
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wchargin/26a19279ba5706c0f7db to your computer and use it in GitHub Desktop.
Save wchargin/26a19279ba5706c0f7db to your computer and use it in GitHub Desktop.
script to answer Quora question
/* http://www.quora.com/Color-and-Colors/Are-there-any-colors-other-than-black-for-which-the-RGB-values-are-the-same-as-the-HSV-values */
#include <stdio.h>
#include <stdbool.h>
float MIN(float a, float b, float c) {
if (a <= b && a <= c) return a;
if (b <= a && b <= c) return b;
return c;
}
float MAX(float a, float b, float c) {
if (a >= b && a >= c) return a;
if (b >= a && b >= c) return b;
return c;
}
/* r,g,b values are from 0 to 1
* h = [0,360], s = [0,1], v = [0,1]
* if s == 0, then h = -1 (undefined)
*
* adapted from:
* http://www.cs.rit.edu/~ncs/color/t_convert.html#RGB%20to%20HSV%20&%20HSV%20to%20RGB
*/
void rgb2hsv(float r, float g, float b, float *h, float *s, float *v) {
float min, max, delta;
min = MIN( r, g, b );
max = MAX( r, g, b );
*v = max;
delta = max - min;
if (max != 0) {
*s = delta / max;
} else {
/* r = g = b = 0 => s = 0, v is undefined */
*s = 0;
*h = -1;
return;
}
if (r == max) {
/* between yellow & magenta */
*h = ( g - b ) / delta;
} else if (g == max) {
/* between cyan and yellow */
*h = 2 + ( b - r ) / delta;
} else {
/* between magenta and cyan */
*h = 4 + ( r - g ) / delta;
}
*h *= 60; /* convert to degrees */
if( *h < 0 ) {
*h += 360;
}
}
inline bool inteq(float x, float y) {
return (int) (x * 255) == (int) (y * 255);
}
inline bool eq(float x, float y) {
float diff = y > x ? (y - x) : (x - y);
return diff < 0.0035; /* epsilon < 1/255 */
}
bool same(float r, float g, float b) {
static float fact = 1 / (float) 360;
float h, s, v;
rgb2hsv(r, g, b, &h, &s, &v);
h *= fact;
/* use `eq' for 0.0-1.0, or `inteq' for 0-255 */
if (inteq(r, h) && inteq(g, s) && inteq(b, v)) {
return true;
}
}
void main() {
int i, j, k;
int count = 0;
float fact = 1 / (float) 255;
printf("Starting search...\n");
for (i = 0; i < 255; i++) {
for (j = 0; j < 255; j++) {
for (k = 0; k < 255; k++) {
float r = i * fact;
float g = j * fact;
float b = k * fact;
if (same(r, g, b)) {
printf("Found a pair: (%d, %d, %d)\n", i, j, k);
count++;
}
}
}
}
printf("Done. %d pair(s) found.\n", count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment