I need to generate to generate random colors in Hex values in my asp.net application to draw a graph .
Random random = new Random();
color = String.Format(\"#
I may have misunderstood the question...
If the issue to avoid similar sequences of colors produced over time, see KMan's response which I think was the first one to suggest that by producing all random values out of the same generator (rather than producing one new generator each time), one avoids the risk of producing a generator with the same seed as a generator previously used.
If the concern is to avoid drawing two "similar" colors in a row, the following response should do. Avoiding two similar colors in a row implies either
The second approach is what is illustrated in the following snippet.
The style is longhand, and the color acceptance criteria is somewhat arbitrary but this should provide a good idea.
Furthermore, by reusing a single Random Number Generator (RNG), one avoid the risk of repeating sequences if somehow the RNG was created each time, and by chance the same seed was used...
const int minTotalDiff = 200; // parameter used in new color acceptance criteria
const int okSingleDiff = 100; // id.
int prevR, prevG, prevB; // R, G and B components of the previously issued color.
Random RandGen = null;
public string GetNewColor()
{
int newR, newG, newB;
if (RandGen == null)
{
RandGen = new Random();
prevR = prevG = prevB = 0;
}
bool found = false;
while (!found)
{
newR = RandGen.Next(255);
newG = RandGen.Next(255);
newB = RandGen.Next(255);
int diffR = Math.Abs(prevR - newR);
int diffG = Math.Abs(prevG - newG);
int diffB = Math.Abs(prevB - newB);
// we only take the new color if...
// Collectively the color components are changed by a certain
// minimum
// or if at least one individual colors is changed by "a lot".
if (diffR + diffG + diffB >= minTotalDiff
|| diffR >= okSingleDiff
|| diffR >= okSingleDiff
|| diffR >= okSingleDiff
)
found = true;
}
prevR = newR;
prevG = newG;
prevB = newB;
return String.Format("#{0:X2}{0:X2}{0:X2}", prevR, prevG, prevB);
}