Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems in generating random colors

I want to generate some random colors in wpf and store them in an array.

Random r;
Color[] colarr = new Color[6];
for (int i = 0; i < colarr.Length; i++)
{
   Color c=new Color();
   r=new Random();
   r.Next();
   c.R = (byte)r.Next(1, 255);
   c.G = (byte)r.Next(1, 255);
   c.B = (byte)r.Next(1, 255);
   c.A = (byte)r.Next(1, 255);
   c.B = (byte)r.Next(1, 255);          
   colarr[i] = c;
}

but all the elements of the array represent one single color. When I debugged the code, I found random colors for every element, but when the code is executed(not in debug mode) same color is generated. This makes clear that the code is correct, there is some problem while execution.

EDIT :

How can I increase the randomness of the colors generated?

like image 379
Tanuj Wadhwa Avatar asked Apr 15 '26 03:04

Tanuj Wadhwa


2 Answers

The problem is that you are making a new instance of random each run. You should set it once.

The default seed for a Random is the system time, which will be the same if you repeat a very fast loop; the time won't change a lot. If you only set it at the start, the Random will work as expected.

I would also suggest you use r.Next(0, 256), since that will give you any value ranging from 0 to 255.

Also, the call to r.Next() after the definition of Color c is completely unnecessary, since you don't use its value.

Random r = new Random();
Color[] colarr = new Color[6];
for (int i = 0; i < colarr.Length; i++)
{
   Color c=new Color();
   c.R = (byte)r.Next(0, 256);
   c.G = (byte)r.Next(0, 256);
   c.B = (byte)r.Next(0, 256);
   c.A = (byte)r.Next(0, 256);
   //c.B = (byte)r.Next(1, 255);  This line isn't needed btw        
   colarr[i] = c;
}
like image 107
antonijn Avatar answered Apr 17 '26 16:04

antonijn


Try like this;

Random r = new Random();
Color[] colarr = new Color[6];
for (int i = 0; i < colarr.Length; i++)
{
   Color c=new Color();
   c.R = (byte)r.Next(0, 256);
   c.G = (byte)r.Next(0, 256);
   c.B = (byte)r.Next(0, 256);
   c.A = (byte)r.Next(0, 256);
   c.B = (byte)r.Next(0, 256);          
   colarr[i] = c;
}

From Marc's answer;

Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.

Read: Random number generator only generating one random number

like image 43
Soner Gönül Avatar answered Apr 17 '26 16:04

Soner Gönül