tags:

views:

82

answers:

3

I currently use the following function to generate a random hexadecimal representation of a color.

function getRandomColor($max_r = 192, $max_g = 192, $max_b = 192) {
    if ($max_r > 192) { $max_r = 192; }
    if ($max_g > 192) { $max_g = 192; }
    if ($max_b > 192) { $max_b = 192; }
    if ($max_r < 0) { $max_r = 0; }
    if ($max_g < 0) { $max_g = 0; }
    if ($max_b < 0) { $max_b = 0; }

    return '#' . dechex(rand(0, 192)) . dechex(rand(0, 192)) . dechex(rand(0, 192));
}

Notice that I set the max value to be 192 instead of 255 for the sole reason that I am avoiding very light colors, for the purpose that I would be using the random color as foreground in a white background.

My question is how do I generate an indefinitely numbered set of colors where there are no colors that are almost the same. e.g.: #D964D9 & #FF3EFF ?

+1  A: 

There are several methods which spring to mind:

  1. Set up a array of n standard colors and interchange them randomly to produce the desired "random" colors.
  2. Fill an array of n colors; generate a random color and check if there is something "close" already in the array. If so, choose another random color.
  3. Select each color as a deterministic sequence, like a simple hash value, designed to not produce duplicate values. Grey code springs to mind.
wallyk
+3  A: 

It might be better to use HSV coordinates. If you don't need white or black, you can set S and V to their maximum values, and generate H values that are not too close to each other (mod 360 degrees). Then convert to RGB.

weiyin
thanks to this I have learned that there are actually only 12 colors that are actually unique (at least that's how it looks in my eyes)
lock
A: 

Your algorithm could randomly generate RGB colors (as it's doing now) however you could for example verify that the two R's are sufficiently different before accepting the color choice. The algorithm could repeat that step (say up to 4...10...N times) for a given R, G and/or B.

while ( (R1 > $max_r/2) && (R2 > $max_r/2) ) {
// Both are in the upper half of range, get a new random value for R1.
}

Other possibilities:

  • Repeat for the lower half of range
  • Further sub-divide ranges (into 1/3's or 1/4's)
  • Repeat for G and B tones
gary comtois