23
3
In CSS, colours can be specified by a "hex triplet" - a three byte (six digit) hexadecimal number where each byte represents the red, green, or blue components of the colour. For instance, #FF0000
is completely red, and is equivalent to rgb(255, 0, 0)
.
Colours can also be represented by the shorthand notation which uses three hexadecimal digits. The shorthand expands to the six digit form by duplicating each digit. For instance, #ABC
becomes #AABBCC
.
Since there are fewer digits in the hex shorthand, fewer colours can be represented.
The challenge
Write a program or function that takes a six digit hexadecimal colour code and outputs the closest three-digit colour code.
Here's an example:
- Input hex code: #28a086
- Red component
- 0x28 = 40 (decimal)
- 0x22 = 34
- 0x33 = 51
- 0x22 is closer, so the first digit of the shortened colour code is 2
- Green component
- 0xa0 = 160
- 0x99 = 153
- 0xaa = 170
- 0x99 is closer, so the second digit is 9
- Blue component
- 0x86 = 134
- 0x77 = 119
- 0x88 = 136
- 0x88 is closer, so the third digit is 8
- The shortened colour code is #298 (which expands to #229988)
Your program or function must accept as input a six digit hexadecimal colour code prepended with #
and output a three digit colour code prepended with #
.
Examples
- #FF0000 → #F00
- #00FF00 → #0F0
- #D913C4 → #D1C
- #C0DD39 → #BD3
- #28A086 → #298
- #C0CF6F → #BC7
Scoring
This is a code-golf challenge, so shortest answer in your language wins! Standard rules apply.
1"adding together the difference between each component of the full colour code and the corresponding component of the shorthand colour code" - this part is confusing. There's no adding anywhere, right? – Grzegorz Oledzki – 2019-06-28T20:21:04.937
3Note that if you simply drop alternate digits then each short colour represents an equal number of full colours, so that could be considered to make a better representation than nearest colour. – Neil – 2019-06-28T20:24:07.913
6Saw this in the Sandbox but forgot to mention that I don't think requiring the
#
adds anything to the challenge. – Shaggy – 2019-06-28T20:24:48.2471@GrzegorzOledzki you're right, that part is confusing. I'll go ahead an remove it because I think the example in that section is enough to explain what I mean. – wrymug – 2019-06-28T20:38:54.303
2May we output in lowercase? – Arnauld – 2019-06-28T21:05:22.600
1@Arnauld yes, that's fine – wrymug – 2019-06-28T21:05:50.087
20x22 is 34, not 30 – Kruga – 2019-07-01T13:13:02.070
1@Kruga thanks, fixed – wrymug – 2019-07-01T14:11:49.837