Expand a greyscale/colour hex code
+1
−0
Consider a type of hexadecimal colour code that supports shorthand for both greyscale and colour:
- A 6 digit code is interpreted as 2 digits for red, followed by 2 for green, then 2 for blue.
- A 2 digit code is greyscale. The 2 digits are used for each of red, green, and blue.
- A 3 digit code is shorthand for a 6 digit code with repeated digits for red, green, and blue.
- A 1 digit code is shorthand for a 2 digit greyscale code with the same 1 digit repeated.
Input
- A colour code in the format "#" followed by 1, 2, 3, or 6 hexadecimal digits.
- You may take input as either a string or any ordered sequence data type.
Output
- A colour code in the format "#" followed by 6 hexadecimal digits.
- The output after the "#" depends on the number of hexadecimal digits in the input as follows:
- Input with 1 digit: output the 1 digit 6 times.
- Input with 2 digits: output the 2 digit string 3 times.
- Input with 3 digits: output each digit twice (rather than the 3 digit string twice).
- Input with 6 digits: output the same 6 digits.
- You may output as either a string or any ordered sequence data type.
Test cases
Test cases are in the format Input : Output
.
#0 : #000000
#A : #AAAAAA
#2E : #2E2E2E
#44 : #444444
#ACF : #AACCFF
#989 : #998899
#777 : #777777
#012345 : #012345
#BBBBBB : #BBBBBB
Scoring
This is a code golf challenge. Your score is the number of bytes in your code.
Explanations are optional, but I'm more likely to upvote answers that have one.
1 answer
+1
−0
Haskell + hgl, 32 24 bytes
tlM$tk6<cy<fiI(rl2~<)eL3
Explanation
-
tlM
map a over the tail of the input ... -
fiI
if ... -
el3
the length is 3 -
(rl2~<)
repeat each letter in place twice. -
cy
cycle the list indefinitely -
tk6
take the first 6 characters.
Reflection
hgl is supposed to be good at structural manipulations like this, so this answer feels a little too long. I think a big part of the issue is that it involves a lot of conditional behavior which is not so robust in hgl.
So I have the following suggestions:
-
fiI
, and its partnerlii
, should have infix variants. This wouldn't actually save any bytes here, but it's a good idea. - Odd length (
od<l
) and even length (ev<l
) should have shortcuts. This would have saved an impressive 3 bytes on an earlier version of this answer, but using the odd length shortcut on this answer would tie. - There should be a flip of
cz
, and it should probably be two bytes. If this existed I could do the extremely weird:
This reshapes the string to the size of the built-in stringtlM$cZ W6<fiI(rl2~<)eL3
"aeiouy"
as a substitute fortk6<cy
. It would save 1 byte.
0 comment threads