Similar colors to input color in hexadecimal format belongs to a set of $\bmod{17}$ remainders

25 Views Asked by At

Given an input color string in the format "#ABCDEF", representing a red-green-blue color, find the shorthand representation of that color that is most similar to the given color. Shorthand representation is in the form "#XYZ", where X, Y, and Z are one of the 16 possible hexadecimal values $(0-9, A-F)$.

The similarity between two colors "#ABCDEF" and "#UVWXYZ" is calculated as $-(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2$.

Example 1: Input: color = "#09f166" Output: "#11ee66" Explanation: The similarity is calculated as $-(0x09 - 0x11)^2 - (0xf1 - 0xee)^2 - (0x66 - 0x66)^2$ = -64 - 9 - 0 = -73. The shorthand color "#11ee66" has the highest similarity.

Example 2: Input: color = "#4e3fe1" Output: "#5544dd"

Constraints:

  • The input color has a length of 7 characters.
  • The first character of color is '#'.
  • The remaining characters of color are either digits or lowercase characters in the range ['a', 'f'].

Solution 1: This is wrong solution where I tried to loop over all possible values r=r+1, g=g+1, b=b+1 in 3 for loops and then find the similarity after combing RGB components in one color and finding similarity with input color.

Solution 2: This is correct solution. We loop in a step of 17 r=r+17, g=g+17, b=b+17 in 3 for loops and then find the similarity after combing RGB in one color and finding similarity with input color. The input color values are rounded off to the nearest valid shorthand representation, which consists of pairs of the same value like "00", "11", "22", ..., "ff". The second approach is more efficient by quantizing the values to multiples of 0x11 (17) and testing eight candidates instead of going through 2 ** 12 loops (256 * 256 * 256 = 4096, which is why we have 2 ** 12 loops). The first approach, which considers all possible combinations, may yield incorrect results because it includes invalid shorthand values that would be truncated back to the closest valid shorthand representation.

Question: in order to find shorthand representation of the color that has the highest similarity to the given color, approach 2 is used by looping through 3 color components using 3 loops each that has a step of r = r+17, g = g+17, b = b+17. When I was looking why we use 17 instead of 1, if we increment by 1, it would return valid return values. Only a value congruent to zero mod 17 can be valid, according to the rules of shorthand abbreviation. I just don't understand why Only a value congruent to zero mod 17 can be valid please?