Theory
Full saturation (like using HSL and similar color schemes) essentially means that you have one full RGB value, one at 0 and one at any other value.
The reason for this is that saturation is based on the difference between the highest and lowest color components and is highest when they are at the extremes. The actual definitions are more complex (and include brightness), but suffice it to say that component 0 and the other of 1 will give maximum saturation.
Algorithm 1
This leads to a relatively simple way to execute it.
- Create a random number from 0 to 1.
- Assign this number randomly to one of the elements R, G, and B.
- Randomly assign zero to one of the remaining items.
- set the end item to 1.
This will give you maximum saturation color is relatively simple.
For the implementation, it is probably easiest to create a random number from 1 to 6 for 6 possible options for which component you assign 0, 1 and a random element, and then use some kind of switch.
This is the simplest algorithm, but not necessarily the simplest implementation, due to selection / branching.
Algorithm 2
The second method, proposed by Jim Michel on the basis of a similar theory, but simply implemented in a slightly different way.
- Generate random values for each of the components R, G and B
- Find the maximum component.
- Find the minimal component.
- Set the maximum component to 1.
- Set the minimum component to 0.
This has the same effect as a single value equal to 1, from one to 0 and one to a random value. The advantage is that it does not require you to use the messy switch statement, but instead, you may run into some messy loops. Also, depending on the accuracy of your components (for example, if you go directly with bytes), then if your average value is actually equal to the top or bottom (or all three are the same), then this may also get reset depending on how you code your algorithm. This will mainly lead to a distortion of randomness, but it is unlikely to be noticeably noticeable.
Code execution for method two is also kindly provided by Jim
int[] rgb = new int[3]; rgb[0] = rnd.Next(256); // red rgb[1] = rnd.Next(256); // green rgb[2] = rnd.Next(256); // blue // Console.WriteLine("{0},{1},{2}", rgb[0], rgb[1], rgb[2]); // find max and min indexes. int max, min; if (rgb[0] > rgb[1]) { max = (rgb[0] > rgb[2]) ? 0 : 2 min = (rgb[1] < rgb[2]) ? 1 : 2; } else { max = (rgb[1] > rgb[2]) ? 1 : 2; int notmax = 1 + max % 2; min = (rgb[0] < rgb[notmax]) ? 0 : notmax; } rgb[max] = 255; rgb[min] = 0; // Console.WriteLine("{0},{1},{2}", rgb[0], rgb[1], rgb[2]);