256-color Xterm-compatible terminals add 240 colors on top of the usual 16 system colors. Colors 16-231 use 6 levels (0, 95, 135, 175, 215, 255) of red, green, and blue, ordered lexicographically. Colors 232-255 are simply 24 levels of gray (8...238 by 10s). To get a better idea of what I'm talking about, see this table.
The Challenge
Your goal is to make a program or function that takes, as input, rgb values, and outputs the number corresponding with the closest Xterm color to that rgb value. Since the 16 system colors (colors 0-15) are often customizable, you will be excluding them from this conversion.
To better define what the "closest" color is, use the Manhattan distance along red, green, and blue components. For example, rgb(10, 180, 90)
is 20 units away from rgb(0, 175, 95)
(color 35) because abs(10 - 0) + abs(180 - 175) + abs(90 - 95) == 20
. If the input color is equally between two or more Xterm colors, output the Xterm color with the highest index.
Examples
R G B Xterm
0 0 0 ==> 16
95 135 0 ==> 64
255 255 255 ==> 231
238 238 238 ==> 255
90 133 140 ==> 66
218 215 216 ==> 188
175 177 178 ==> 249
175 0 155 ==> 127
75 75 75 ==> 239
23 23 23 ==> 234
115 155 235 ==> 111
Rules
- Standard loopholes are forbidden
- Your program or function is allowed to take rgb values in any reasonable format, including:
- Separate arguments for red, green, and blue
- A list, tuple, dictionary, or similar
- Delimiter-separated string or stdin
- Hex colors (e.g.
#ff8000
)
- You may assume that all r, g, and b, values will be integers between 0 and 255.
- Since the 16 system colors are to be excluded from the mapping, all outputs should be in the range 16...255.
This is code-golf, so shortest code wins.