#C6424. Color Class Operations
Color Class Operations
Color Class Operations
You are required to implement a Color
class which represents a color in RGB format and supports several operations including conversion to hexadecimal, conversion to HSL, and darkening the color by a given percentage.
The class must support the following methods:
to_hex()
: Returns the hexadecimal string representation of the color in the format#RRGGBB
.to_hsl()
: Returns the HSL (Hue, Saturation, Lightness) representation as a tuple where Hue is an integer (in degrees) and Saturation and Lightness are floats rounded to two decimals. Use the standard formulas:</p>\( L = \frac{\max(r,g,b) + \min(r,g,b)}{2} \)
\( \text{if } \Delta = \max(r,g,b)-\min(r,g,b)=0 \text{ then } H = S = 0 \)
\( \text{otherwise, } S = \begin{cases} \frac{\Delta}{\max(r,g,b)+\min(r,g,b)} & L\leq0.5\\ \frac{\Delta}{2.0-\max(r,g,b)-\min(r,g,b)} & L>0.5 \end{cases} \)
and Hue is determined based on which of RGB is maximum.
darker(percentage)
: Returns a new Color instance that is a darker shade by reducing each RGB component by a factor of \( (1-\text{percentage}) \). Here,percentage
is a float between 0 and 1.
Input/Output Interaction:
The program will process multiple queries. Each query begins with an integer indicating the type of operation, followed by the corresponding parameters:
- Type 1: Convert to hexadecimal. Input:
1 r g b
- Type 2: Convert to HSL. Input:
2 r g b
- Type 3: Darken the color. Input:
3 r g b percentage
For each query, output the corresponding result on a new line. For HSL, output the three components separated by a space (Hue as an integer, Saturation and Lightness as floats rounded to 2 decimals).
inputFormat
The first line of input contains an integer Q (Q ≥ 3) representing the number of queries. Each of the following Q lines contains a query. The queries are in one of the following formats:
1 r g b
- where r, g, b are integers (0-255) for converting to hexadecimal.2 r g b
- where r, g, b are integers (0-255) for converting to HSL.3 r g b percentage
- where r, g, b are integers (0-255) andpercentage
is a float between 0 and 1 for darkening the color.
outputFormat
For each query, output the result on a new line:
- For type 1 queries, output the hexadecimal color as a string in the format
#RRGGBB
. - For type 2 queries, output the HSL values separated by a space. Hue must be an integer and Saturation and Lightness rounded to two decimals.
- For type 3 queries, output the hexadecimal representation of the darkened color.
3
1 255 0 0
2 0 255 0
3 0 0 255 1.0
#FF0000
120 1.00 0.50
#000000
</p>