Forum Moderators: coopster

Message Too Old, No Replies

how to generate unique hexcolors?

         

PHPycho

4:14 am on Apr 13, 2007 (gmt 0)

10+ Year Member



Hello forums!
I am getting problem in generating unique hexcolors ie ##*$!#*$!
Can anybody provide me the help regarding generation of unique hexcolors?
Thanks to all of You in advance..

mcavic

4:54 am on Apr 13, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What do you mean by unique?

PHPycho

6:10 am on Apr 13, 2007 (gmt 0)

10+ Year Member



Unique means:
Each time the generated color should be unique to the previous one..
Anyway thanks for the reply

whoisgregg

2:19 pm on Apr 13, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What does your random hex color generator code look like so far? :)

mooger35

6:48 pm on Apr 13, 2007 (gmt 0)

10+ Year Member



do you have to use hex colors?

what about using rgb format? Then just randomize three numbers between 0 and 255?

example

rgb(230, 232, 250) would give you silver.

whoisgregg

8:05 pm on Apr 13, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Here's a little function to spit out as many unique hex colors as you need. Note it doesn't care how similar the colors are, only that they are unique. So, you could end up with FFFFFF, FFFFFE, FFFFFD, etc.

Try not to generate more than a thousand or so. Each new color needs to be compared to all previous colors so the processing time increases exponentially. Maybe quadratically? Or factorially? I don't know, it just gets slower and slower. ;)

<?php
function generateUniqueHexColors($quantity=10){
if($quantity >= (254*254*254)){ // Don't try to generate the full set of hex colors this way.
return false;
}
$colors = array();
$quantity = (intval($quantity) == 0)? 1 : intval($quantity);
for($i=0; $i<$quantity; $i++){
$color = sprintf("%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
while( in_array($color, $colors) ){
//echo $i.': '.$color.' already existed<br />'; // uncomment to debug
$color = sprintf("%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
}
$colors[] = $color;
}
return $colors;
}
$colors = generateUniqueHexColors(1000); // anything over 1000 is rather slow
/*/ To test that it worked:
$unique = array_unique($colors);
if( $colors!= $unique ){ echo '<h1>Failed!</h1>'; } else { echo '<h1>Success!</h1>'; }
print_r($colors);
// */
echo '<style type="text/css">div.b { width: 20px; height: 20px; float:left; }</style>';
foreach($colors as $c=>$v){
echo '<div style="background-color: #'.$v.'" class="b"></div>';
}
?>