-1

The below function have the problem that there is not gurantee of distinguishable difference in the 2 color codes though it will generate distinct solid colors.

private Color[] GenerateNewColor(int count) 
{ 
    Color[] colors=new Color[count*2]; 
    for (int i = 0; i < count*2; i++) 
    { 
        var values = Guid.NewGuid().ToByteArray().Select(b => (int) b); 
        int red = values.Take(5).Sum()%255; 
        int green = values.Skip(5).Take(5).Sum()%255; 
        int blue = values.Skip(10).Take(5).Sum()%255; 
        // 
        colors[i] = Color.FromArgb(255, red, green, blue); 
    } 
    HashSet<Color> hashedcolors=new HashSet<Color>(colors); 
    return hashedcolors.ToArray(); 
}

Below function will evenly divide the the color codes from #000000 to #ffffff but it does not gurantee of the solid colors. Moreover if the number of colors is less say 5 then it will generate the shade of Black only

private string[] GenerateNewColorByAdding(int count) 
{ 
    long hexmin=0X000000; 
    long hexmax = 0XFFFFFF; 
    long adder = Convert.ToInt64(hexmax)/count; 
    string[] s=new string[count]; 
    for (int i = 0; i < count; i++) 
    { 
        hexmin = hexmin + adder; 
        s[i] = String.Format("#{0:X6}" ,hexmin); 
    } 
    return s;   
}

So I would like to get n number of solid colour's each should be visibility distinct to each other.

Example: if n=50 Requirement 1 : 50 Solid(no transparency) colour's should be generated. Requirement 2 : each one of them should be visibly distinct to each other like : red,green,blue,orange...etc.,

Note : here 'n' could be maximum 100.

Noctis
  • 11,507
  • 3
  • 43
  • 82
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67

1 Answers1

0

Since there are three independent variables (red, green and blue), you can take the cube root of the number of distinct colours you want, and use that to combine that many values each of red, green and blue to give the required number of colours.

Perhaps something like this would work for you:

public IEnumerable<Color> DistinctColors(int n)
{
    int m = (int)Math.Ceiling(Math.Pow(n, 1/3.0));

    for (int green = 0; green <= m; ++green)
    {
        for (int blue = 0; blue <= m; ++blue)
        {
            for (int red = 0; red <= m; ++red)
            {
                if (n-- == 0)
                    yield break;

                int r = (int)(0.5 + red*255.0/m);
                int g = (int)(0.5 + green*255.0/m);
                int b = (int)(0.5 + blue*255.0/m);

                yield return Color.FromArgb(r, g, b);
            }
        }
    }
}

[EDIT] Changed the order of RGB generation so that generally more red shades than green shades will be generated (since that seems to give better results).

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276