Problem in generating random colors - asp.net and c# -


i need generate generate random colors in hex values in asp.net application draw graph .

 random random = new random();  color = string.format("#{0:x6}", random.next(0x1000000));  

the above code generates random color codes . problem time generate similar colors previous colors. because of using graph purpose need generate different colors. ideas....

i may have misunderstood question...
if issue avoid similar sequences of colors produced on time, see kman's response think first 1 suggest producing random values out of same generator (rather producing 1 new generator each time), 1 avoids risk of producing generator same seed generator used.

if concern avoid drawing 2 "similar" colors in row, following response should do. avoiding 2 similar colors in row implies either

  • the use of mathematical logic (but there risk functions used not cover spectrum of possible colors decent random number generator would)
  • drawing true random colors, refusing them (and trying anew) when deemed similar.

the second approach illustrated in following snippet.
style longhand, , color acceptance criteria arbitrary should provide idea.
furthermore, reusing single random number generator (rng), 1 avoid risk of repeating sequences if somehow rng created each time, , chance same seed used...

  const int mintotaldiff = 200;    // parameter used in new color acceptance criteria   const int oksinglediff = 100;    // id.    int prevr, prevg, prevb;  // r, g , b components of 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);            // take new color if...           //   collectively color components changed           //   minimum           //   or if @ least 1 individual colors changed "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);   } 

Comments

Popular posts from this blog

400 Bad Request on Apache/PHP AddHandler wrapper -

Add email recipient to all new Trac tickets -

php - Change action and image src url's with jQuery -