13
\$\begingroup\$

Input

A single hex 6-digit colour code, capital letter, without #. Can also be a 24-bit integer if you prefer.

Output

The closest HTML color name (e.g red, or dark-salmon, as defined as https://www.w3schools.com/colors/colors_names.asp or see below). Distance is defined by summing the difference in red, green and blue channels.

Examples

FF04FE: magenta

FFFFFF: white

457CCB (halfway between steelblue and darkslateblue): steelblue (round up)

Rules

  • Standard loopholes apply.
  • Standard I/O applies
  • Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g red = #FF0000 = 16711680 > blue = #0000FF = 256
  • If one hex code has two names (e.g. grey and gray), output either.
  • Outputs can be capitalised and hyphenated how you like
  • Trailing/preceding spaces/newlines are fine
  • You must output the names in full.
  • This is , so shortest answer in bytes wins.

Colors

As per suggestion in the comments, here are all of the color names with respective hex values in CSV format:

Color Name,HEX
Black,#000000
Navy,#000080
DarkBlue,#00008B
MediumBlue,#0000CD
Blue,#0000FF
DarkGreen,#006400
Green,#008000
Teal,#008080
DarkCyan,#008B8B
DeepSkyBlue,#00BFFF
DarkTurquoise,#00CED1
MediumSpringGreen,#00FA9A
Lime,#00FF00
SpringGreen,#00FF7F
Aqua,#00FFFF
Cyan,#00FFFF
MidnightBlue,#191970
DodgerBlue,#1E90FF
LightSeaGreen,#20B2AA
ForestGreen,#228B22
SeaGreen,#2E8B57
DarkSlateGray,#2F4F4F
DarkSlateGrey,#2F4F4F
LimeGreen,#32CD32
MediumSeaGreen,#3CB371
Turquoise,#40E0D0
RoyalBlue,#4169E1
SteelBlue,#4682B4
DarkSlateBlue,#483D8B
MediumTurquoise,#48D1CC
Indigo,#4B0082
DarkOliveGreen,#556B2F
CadetBlue,#5F9EA0
CornflowerBlue,#6495ED
RebeccaPurple,#663399
MediumAquaMarine,#66CDAA
DimGray,#696969
DimGrey,#696969
SlateBlue,#6A5ACD
OliveDrab,#6B8E23
SlateGray,#708090
SlateGrey,#708090
LightSlateGray,#778899
LightSlateGrey,#778899
MediumSlateBlue,#7B68EE
LawnGreen,#7CFC00
Chartreuse,#7FFF00
Aquamarine,#7FFFD4
Maroon,#800000
Purple,#800080
Olive,#808000
Gray,#808080
Grey,#808080
SkyBlue,#87CEEB
LightSkyBlue,#87CEFA
BlueViolet,#8A2BE2
DarkRed,#8B0000
DarkMagenta,#8B008B
SaddleBrown,#8B4513
DarkSeaGreen,#8FBC8F
LightGreen,#90EE90
MediumPurple,#9370DB
DarkViolet,#9400D3
PaleGreen,#98FB98
DarkOrchid,#9932CC
YellowGreen,#9ACD32
Sienna,#A0522D
Brown,#A52A2A
DarkGray,#A9A9A9
DarkGrey,#A9A9A9
LightBlue,#ADD8E6
GreenYellow,#ADFF2F
PaleTurquoise,#AFEEEE
LightSteelBlue,#B0C4DE
PowderBlue,#B0E0E6
FireBrick,#B22222
DarkGoldenRod,#B8860B
MediumOrchid,#BA55D3
RosyBrown,#BC8F8F
DarkKhaki,#BDB76B
Silver,#C0C0C0
MediumVioletRed,#C71585
IndianRed,#CD5C5C
Peru,#CD853F
Chocolate,#D2691E
Tan,#D2B48C
LightGray,#D3D3D3
LightGrey,#D3D3D3
Thistle,#D8BFD8
Orchid,#DA70D6
GoldenRod,#DAA520
PaleVioletRed,#DB7093
Crimson,#DC143C
Gainsboro,#DCDCDC
Plum,#DDA0DD
BurlyWood,#DEB887
LightCyan,#E0FFFF
Lavender,#E6E6FA
DarkSalmon,#E9967A
Violet,#EE82EE
PaleGoldenRod,#EEE8AA
LightCoral,#F08080
Khaki,#F0E68C
AliceBlue,#F0F8FF
HoneyDew,#F0FFF0
Azure,#F0FFFF
SandyBrown,#F4A460
Wheat,#F5DEB3
Beige,#F5F5DC
WhiteSmoke,#F5F5F5
MintCream,#F5FFFA
GhostWhite,#F8F8FF
Salmon,#FA8072
AntiqueWhite,#FAEBD7
Linen,#FAF0E6
LightGoldenRodYellow,#FAFAD2
OldLace,#FDF5E6
Red,#FF0000
Fuchsia,#FF00FF
Magenta,#FF00FF
DeepPink,#FF1493
OrangeRed,#FF4500
Tomato,#FF6347
HotPink,#FF69B4
Coral,#FF7F50
DarkOrange,#FF8C00
LightSalmon,#FFA07A
Orange,#FFA500
LightPink,#FFB6C1
Pink,#FFC0CB
Gold,#FFD700
PeachPuff,#FFDAB9
NavajoWhite,#FFDEAD
Moccasin,#FFE4B5
Bisque,#FFE4C4
MistyRose,#FFE4E1
BlanchedAlmond,#FFEBCD
PapayaWhip,#FFEFD5
LavenderBlush,#FFF0F5
SeaShell,#FFF5EE
Cornsilk,#FFF8DC
LemonChiffon,#FFFACD
FloralWhite,#FFFAF0
Snow,#FFFAFA
Yellow,#FFFF00
LightYellow,#FFFFE0
Ivory,#FFFFF0
White,#FFFFFF
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Related (basically the opposite task) \$\endgroup\$
    – Arnauld
    Jun 30, 2019 at 8:51
  • 2
    \$\begingroup\$ Isn't Turquoise (#40E0D0) the closest color to #40FFEA with a sum of differences of \$57\$? (vs \$85\$ for Aqua and Aquamarine) \$\endgroup\$
    – Arnauld
    Jun 30, 2019 at 13:23
  • 1
    \$\begingroup\$ shouldn't round up be steelblue instead of darksleetblue? \$\endgroup\$
    – tsh
    Jul 2, 2019 at 6:00
  • \$\begingroup\$ For anyone else doing this challenge, here are the duplicated colors you can choose one of: Aqua/Cyan; DarkSlateGray/DarkSlateGrey; DimGray/DimGrey; SlateGray/SlateGrey; LightSlateGray/LightSlateGrey; Gray/Grey; DarkGray/DarkGrey; LightGray/LightGrey; Fuchsia/Magenta. I had only filtered out the duplicated grey colors, but not the other two. So I was getting off-set errors due to mismatches in my string and integer lists.. >.> Figured I'd post this here to prevent others from making the same mistake I did. \$\endgroup\$ Jul 2, 2019 at 13:10

7 Answers 7

17
\$\begingroup\$

C# (Visual C# Interactive Compiler), 231+21=252 bytes

s=>Color.FromArgb(Convert.ToInt32(s,16));f=s=>Enum.GetNames(typeof(KnownColor)).Select(x=>Color.FromName(x)).Where(x=>!x.IsSystemColor&x.A>254).OrderBy(x=>Math.Abs(x.R-C(s).R)+Math.Abs(x.G-C(s).G)+Math.Abs(x.B-C(s).B)).First().Name

Explanation:

using System.Drawing; //System library that handles Colors in C#

C=s=>Color.FromArgb(Convert.ToInt32(s,16));        //helper method. receives a hex string and returns it's Color

f=s=>Enum.GetNames(typeof(KnownColor))             //collection of color names from the System.Drawing.KnownColor enum
         .Select(x=>Color.FromName(x))             //convert the color names to Colors
             .Where(x=>!x.IsSystemColor&x.A>254)   //filter out unwanted colors
                 .OrderBy(x=>Math.Abs(x.R-C(s).R)  //order by increasing distance
                            +Math.Abs(x.G-C(s).G)
                            +Math.Abs(x.B-C(s).B)) 
                     .First().Name                 //return the closest color's name

For some reason, Tio complains that the namespace 'Drawing' does not exist in the namespace 'System', despite the source project Mono stating it's compatible. It works fine in VisualStudio though.

EDIT: apparently it hasn't been implemented into Tio yet!

Try it online!

\$\endgroup\$
3
  • 7
    \$\begingroup\$ C# out-golfing the golfing languages for once. There's a first... \$\endgroup\$ Jul 1, 2019 at 18:33
  • 2
    \$\begingroup\$ I'm surprised Javascript doesn't have a way to access the list but C# does \$\endgroup\$
    – JollyJoker
    Jul 2, 2019 at 10:35
  • 1
    \$\begingroup\$ @JollyJoker This Node.js answer does import a package containing the data. \$\endgroup\$
    – Arnauld
    Jul 2, 2019 at 15:07
14
\$\begingroup\$

Node.js, 1488 bytes

Takes input as a 24-bit integer. Outputs in lower case.

v=>(require('zlib').inflateRawSync(Buffer('TVRbm6o4EPxLE27CowziDOiIV+bwFkkrWUPCBBg/9tdvLurZFzGX7uqqrs6Z4fr2xvHv5OYEy9uZjRC3QOjY6r/oaH4X+ugqAXiWI/P1M28AzGxQPWHuBBkB6PrbpCPmyZs+GEb5Mwrag/O9sEn7TlJ+NSnCr4TRFk7z/+25mc7l5i0lnF6bQef6Pn6tiCBXkHo12yxTpo96wCbEqfbxRUjoB7tcxfvn0fJ4POgyeoYHuEo8IafINaY59co8exT1uJ+Uq/hVsn8KUykmzDTqzin6AcD8n/nb3Sur3nDSD9cmegUf5hHlhF6F6ySOviwY/bWwi/UO1ZiA4baIj1EtJL8wcbf8gspLJJyhrnE3yo6BExUbmx3/jLjFSis4pitCW83I/SrTVyEo3uQGiEh8Rpvi80U8+OMXVrXnTnTKowf7Z7i/fFsxfOdWx9l6XjdYDhLGHrxwvvkL75fqKwRHoS3RtahFsDEl5U8TRMudBbXrVP/8UsFgcOMP4xwJBPmlsVeLr8AH7J56TAiDsxR3nmTvRulHf4LotDQJzQptlsgyeFTxeUr1bYuwT/cdZlbyoDog0wRZN5TMy3wCpgS3PCNn0VPgHM927smgBvvvwhpeCRc/7GYEOq0KE2TjZ3mkIf6avPiOLd+nVVAQvXfiTmxr/ez9QlVvJa1vaLc01K6CEeBSkLDyfcvGVulk6zcp+slU5HrZUt++NfhG0Tote8p+QXpRVtgYy1mpGZb+h3Ye5npxWKQdyDF0dnUjaqEbHZzmswHzRbl4KKmmIt+ehob2A4OgLP0HfpI5r+Lm8VEzfaEgL9jVkra94GV8uGLK+7OQArnrTcfGVo3Z4TxKNt2FICgLtwbKTPYs8hj+Ba4kCedLO0eYtYK7u31p8wdlFZrWPdFz13ZdDQpmTpgHRobc32BGa+Nc92vWCA4TgTtKEvzvKCHtMSdWPd8LonsDeEBbd3YGegUvL+4NHaBvxQ2KlvKhloBbVEXXRvSDOfOCuLClOX78hflAf0YwJ6uZmiUOvKqshM86rSvQHzUNRD2rKsP2XYu1zOcPc89c/UZ2lN/cU6jYcPWoAYnyZBAtHoRfxY0Y9DGKCsPWizbWuPqq8xlae5mqPLS222Vgdk3Wz8hEVwtdlJd8d4Drphsvl+2HeuPxP8IQ2HutUO9LTzkKyjPtFbG0Vf2flOHgcGaY1w0Qg0JQoprR4QmryG6/eTZPqd434ZuazL5RtKtEv2LKlbf8yEDFKQtdLoInB/WyKR4Gtuq5uM+tSvu1KdougpD+Cjktza30Pw','base64'))+'').replace(m=/([a-z]+)([^a-z]+)/g,(_,s,d)=>[e=0,8,16].map(x=>e+=Math.abs((v>>x&255)-(t>>x&255)),t+=parseInt(d,36))|e>m||(o=s,m=e),t=0)&&o

Try it online!

How?

The compressed string is 1683 characters long and looks like that:

"black0navy3KdarkblueBmediumblue1Ublue1EdarkgreenJK1green5J4(…)lightyellow68ivoryGwhiteF"

The colors are ordered from lowest to highest value. Each color is encoded as its name in lower case followed by the difference between its value and the previous value in base-36 and in upper case:

black[0]        | 0x000000 + 0     --> 0x000000
navy[3K]        | 0x000000 + 128   --> 0x000080
darkblue[B]     | 0x000080 + 11    --> 0x00008B
mediumblue[1U]  | 0x00008B + 66    --> 0x0000CD
blue[1E]        | 0x0000CD + 50    --> 0x0000FF
darkgreen[JK1]  | 0x0000FF + 25345 --> 0x006400
green[5J4]      | 0x006400 + 7168  --> 0x008000
...             | ...
lightyellow[68] | 0xFFFF00 + 224   --> 0xFFFFE0
ivory[G]        | 0xFFFFE0 + 16    --> 0xFFFFF0
white[F]        | 0xFFFFF0 + 15    --> 0xFFFFFF

Commented

v =>                            // v = input
  ( require('zlib')             // using zlib,
    .inflateRawSync(            // inflate the
      Buffer(                   //   buffer obtained by
        'TVRbm(…)Pw',           //     converting this string
        'base64'                //     encoded in base-64
      )                         //
    ) + ''                      // and coerce it back to a string
  ).replace(                    // on which we invoke replace():
    m =                         //   initialize m to a non-numeric value
    /([a-z]+)([^a-z]+)/g,       //   for each color encoded as ...
    (_, s, d) =>                //   ... s = name, d = delta in base-36:
      [e = 0, 8, 16]            //     using x = 0 for blue, 8 for green and 16 for red,
      .map(x =>                 //     compute the error e:
        e +=                    //       add to e:
          Math.abs(             //         the absolute value of the difference between
            (v >> x & 255) -    //           the component of the target color
            (t >> x & 255)      //           and the component of the current color
          ),                    //
        t += parseInt(d, 36)    //       start by adding the delta to t
      ) | e > m ||              //     end of map(); if e is less than or equal to m:
        (o = s, m = e),         //       update o to s and m to e
    t = 0                       //   start with t = 0
  ) && o                        // end of replace(); return o
\$\endgroup\$
4
  • \$\begingroup\$ Why not compress your codes with the data string together then eval it? Had you tried this? \$\endgroup\$
    – tsh
    Jul 2, 2019 at 5:53
  • \$\begingroup\$ @tsh The JS code doesn't compress well enough to compensate for the overload induced by base64 encoding. So it would be longer. It could be rewritten to make it more deflate-friendly (e.g. by unrolling the map loop) but I doubt that would be enough. \$\endgroup\$
    – Arnauld
    Jul 2, 2019 at 9:45
  • \$\begingroup\$ Couldn't you generate the color names yourself? There's probably a better/faster way of doing it, but you could just brute-force it: q=i=>{b=document.createElementd;b.style.color=i;document.body.appendChild(b);h=getComputedStyle(b).color;y=h.slice(4,-1).split(",").map(e=>e.trim());return h!="rgb(36, 39, 41)"?[y.reduce((a,e)=>a+parseInt(e),0),parseInt(y.map(e=>parseInt(e).toString(16).padStart(2,"0")).join``,16)]:0};a=[];for(i=0,t="0";i<7988090793663851220822006848646;i++,t=i.toString(36)){(!t.match(/\d/g)&&q(t))?a.push([t,...q(t)]):0} (note that rgb(36, 39, 41) changes with the... \$\endgroup\$ Feb 4, 2020 at 20:21
  • \$\begingroup\$ ...stylesheet, this one works with StackExchange - it's just the default font color). Also, I don't know if this counts, since it would take literal days to run, but I've tested it on a small scale and can see it works (try replacing 7988090793663851220822006848646 with 39999) \$\endgroup\$ Feb 4, 2020 at 20:22
9
\$\begingroup\$

Jelly, 1015 914 bytes

“¥.⁻ḲU3ŒẆȯ§.eḊC¤ŀ"}Ʋ59£Uŀ'⁶ɠıṇȥLcṆɓ?^¢Ỵɠ.ȮẆẆḊqʠu½ỊƑfĠ⁴ µ¥ɓƭÑUC½ṁUĿẆṃ⁹S/÷Ɓɗ>ṭ"»Ḳ33r64¤,Ọy“µṂFŀƲOḌẇȤạ2œxṾk,E.LẸpḄ2s⁵Ṛç¦ṆkAẋ=çw©ḌĊẒƤm`;ṄȧṄİɦbṠṆṛ⁴Ḟ[CƊėQẏƑ<:⁾Þḍ?çⱮ3ƈṗ¬!7Hẏywœ⁽Ẉ¤ṾƈpHṗ(⁾ƲḢdƲḃ'¦ṇ9ẏP¡ċ⁻ȤẒṬf§®ṬẒpJÞẒẸṪÄƊhḊḃ7ʠ%ƈėc+ġȦı©ḄO⁸ṗ:WṠß@Ä|ż_g¹Ʋ®[*ẹ5¡Ẹßė¶~[ȷ'ȧẊṖZẋ¦ẉ7Ġ⁽ė⁽ƁLP`²¶⁶* Ġv|$ṭⱮẋ_ƭø¦Ẇ-*ɓɼhCUṙƭƭƓS7Ø⁵¤³¢Ʋẉ!§ḟƇṣḟṛḳṠƬ4ẓḢTḌZżƇȦQxw}ḃçṣȮv⁷ȤĊẏyNỵʠÄ⁸hLġị³TİọȧfÞȤTO&ṡ°⁼`WẹạẇḂvðFmż]ɦo½ƓṂḟȯ#Æ⁺T)ṃç=ḣṆø⁽Wpʂqṫ&⁷¶S®¢ð:\ṚMĖḌ½⁽_ạ⁵]Xlȷg¿£⁺x0ṁo8ẒṛżøuɲẈ®§Bṡr:ċ³ḷb|Mku¬V°ḟƲ!ɦɠ4¬>ḷ^XḶɼ5[ṇƑȮ.XȮƙẎbḊÐþFæṁoOṗ⁺mṪ-&ƊṅƑḋ$!`€ɓḥƤ¡ɗbH⁻ḃÄ⁵!Ñėḅƈḳm⁴ḳcÐⱮ⁷ỤḍġḷȥṀSĖ»Ḳ
“⁸¢!İƝ\8¢[V⁸¢Ñ"ĠƙḶ-Æ⁷⁾Æ⁵¢⁸¢ƙhLṂS×®Ẓ©Aḅ¦ṚÆ&nj£ÇØ¿waþM=ÆḂḌ¢³(Ñḷx¦DẊ¢Aẓ©ḋ¬!ƁV  ṾÐẉœ¦2Ä¢⁼C®⁶ẇ£ḋṀ¤çẠÐȧIæḌH€5ẋ¥®⁹µ⁻£⁴⁸¢AƇ¢⁸¢£*ç-Ụz¬>ƈ£ʋ¢^ạṭ(ÇṪĠ¤Çŀ¬ÇḞ¢ṪĠÐCȥṖÞ¦ø}×⁹YÐƬAÇ×CÆævÇ#©ḥƙ£sVṀṙ¤ỊAÞtỤ¦AǬ⁶ʠ¤⁼ƈµ£ŒÞ¿§Œ÷~2~Ðɲċ×⁻¤SƤÐ}Z¦Fƙ°¹£Ḣ©£Ṁx£⁹j£Ƒs¤ɓ8¬_ḶØz°®ʂƬÐḢ@¢ẉ€¦ỴA¢Ä8gß-Ė⁸¿zṛ¤mGKÄœ>jµ\ạ¥>R¢ƤÐƤœⱮpµỴI¤Œ¤a<[Ɱa]ṠŒɲB"'(?ŀÆȦ6ȯœ|Dy¿1€ƤØ-WXßm€v¤Uнµẋ¦iœg€Ḥ£0-‘©ṛ®Ḣ¤⁺;$%¡3¤®Ð¿Ḋḅ249:3ÄŻ,b⁹UạN,§ʋ@€/MṪị¢

Try it online!

Thanks to @Arnauld for a suggestion that saved 41 bytes!

Full program. Takes colour as 24-bit integer as its argument and returns the colour name.

Explanation

Helper link

Colour names. Stored using compressed string, but with common words replaced by single ASCII characters in range 33 to 64

“¥...»                  | Compressed string "blue brown coral..."
      Ḳ                 | Split at spaces
       33r64¤,          | Pair the numbers 33 to 64 with these words [[33,34,35,...],["blue","brown","coral",...]]
              Ọ         | Convert the numbers to Unicode characters [["!",'"',"#",...],["blue","brown","coral",...]]
               y“µ...»  | Translate the compressed string "black navy %! ..." using the mapping generated above
                      Ḳ | Split at spaces

Main link

Stage 1: Start generating list of colour numbers. The increments between colour numbers are stored as between 1 and 3 base 249 digits. The increment has been multiplied by 3, converted to base 249 and then the number of digits minus 1 has been added to the least significant digit, before reversing the order of digits.

“⁸...‘©                | Copy compressed integers 136,1,33,198,... to register
       ṛ               | Right value (will yield value of the following):
                 ¤®Ð¿  | - While the register is non-empty, do the following, collecting values as we go:
        ®Ḣ¤            |   - Take the first value from the list held in the register, popping it from the list, x
              %¡3      |   - Repeat the following (x mod 3 times)
           ⁺;$         |     - Concatenate the first value from the list held in the register, popping it from the list
                     Ḋ | Remove the first item (will be 'None')

Stage 2: Finish generating colour numbers and look up the input

ḅ249                     | Convert from base 249 to integer
    :3                   | Integer divide by 3
      Ä                  | Cumulative sum: 128,139,205,255,25600,...
       Ż                 | Prepend zero
        ,                | Pair with input
         b⁹              | Convert to base 256: [[0],[128],[139],[205],[255],[100,0],...], [input in base 256]
           U             | Reverse order of innermost lists (so RGB becomes BGR, GB becomes BG and B remains as B); this is because colours with no red component will be a list with only two members, and colours with only blue will just have one member
                ʋ@€/     | Reduce using the following as a dyad for each; effectively calls the following once for each colour with the reversed base-256 colour as left argument and the reversed base-256 input as right
            ạ            | - Absolute difference of the colour and the output of stage 1
             N           | Negate
              ,          | - Pair with the colour
               §         |   - Sum each of these
                    M    | Indices of maximum
                     Ṫ   | Tail (will be the index of the largest colour value)
                      ị¢ | Index into helper link

Colours are reversed before comparing because colours with no red component (for example) will end up as a 2 component list.

TIO link generates 10 random colours and shows the output so will be different each time.

\$\endgroup\$
6
  • \$\begingroup\$ Input can be 24-bit. I already said standard I/O applies. \$\endgroup\$ Jun 30, 2019 at 19:15
  • \$\begingroup\$ @GezaKerecsenyi Thanks. You also said it needed to be a six-digit hex string, so it would be good to clarify in the question. \$\endgroup\$ Jun 30, 2019 at 19:19
  • \$\begingroup\$ Would it be shorter to encode \$i\times 4+n\$ (or maybe \$i\times 3+n\$), where \$i\$ is the increment and \$n\$ is the number of additional base-250 numbers required to fully describe it? (I think that would fit on 341 numbers instead of 392). \$\endgroup\$
    – Arnauld
    Jun 30, 2019 at 20:48
  • \$\begingroup\$ Here is some JS code to illustrate what I mean. (This is a fixed version with encoding + decoding. Sorry about the multiple posts.) \$\endgroup\$
    – Arnauld
    Jun 30, 2019 at 21:48
  • \$\begingroup\$ @Arnauld thanks. I needed up using base 249. In brief, I multiplied the increments by 3, converted to base 249, reversed the order of digits and added length-1 to the first digit. These are then encoded as Jelly characters. For decoding, I pop the first digit, then pop a further (first digit mod 3) digits and concatenation them (reversing the order in the process). I repeat until no digits are left. This is then converted back from base 249 to integer. The reason for 249 is that 250, the least significant digit isn’t necessarily a multiple of 3. \$\endgroup\$ Jun 30, 2019 at 21:55
3
\$\begingroup\$

Wolfram Language (Mathematica), 164 bytes

Note: This only works in Mathematica 12.0 due to a bug in previous versions. This also means there is no TIO link.

g[c_]:=Last@Keys@SortBy[Round[255List@@@<|"HTML"~ColorData~"ColorRules"~Join~{"RebeccaPurple"->RGBColor@"#639"}|>],{-Total@Abs[IntegerDigits[c,256,3]-#]&,Total,#&}]

Defines the function g, which takes an integer as input. Test cases:

AssociationMap[g, {327581, 3483113, 2820178, 4358965,
  2058772, 13569770, 8698378, 2897368, 3896382, 12856883}]

(* <|
  327581 -> "MediumSpringGreen",
  3483113 -> "RoyalBlue", 
  2820178 -> "MidnightBlue",
  4358965 -> "DarkOliveGreen", 
  2058772 -> "ForestGreen", 
  13569770 -> "Magenta",
  8698378 -> "Olive",
  2897368 -> "RoyalBlue",
  3896382 -> "DarkOliveGreen",
  12856883 -> "Brown"
|> *)

Unfortunately, quite a few bytes are wasted on adding "RebeccaPurple" to the built-in list of colors, which is missing for some reason. The rest is pretty straightforward, we just sort the colors by their distance to the input, breaking ties with the sum of channel values and then the absolute ordering.

\$\endgroup\$
1
2
\$\begingroup\$

JavaScript (Firefox), 1050 bytes

c=>(b=document.body,_.match(/.[a-z]*/g).map(t=>getComputedStyle(b,b.style.color=t).color.match(/\d+/g).map((v,i)=>s+=Math.abs((c>>16-8*i&255)-v),s=0)|m>=s&&(m=s,r=t),r=m=c),r)
_='BlackNavy}~x~B2e}|G^ETeU}cy@Deeps,}t`xs*LimeS*Cy@Midnight~Dodg9~{s:GFo^1|S:|}s]JLime|xs:|T`RoyU~Steel~}s]~xt`Indigo}o6|Cadet~C?nfl59~Rebeccap<xa;DimJS]~O6drabS]J{s]Jxs]~Lawn|Chart^useA;Maro4P<O6GrayG^yS,{s,B2ev[}0}m+Saddleb>}s:|{|xp<}v[7|}?/YZ|SiEnaB>}J{~G^EyZ7t`{1eel~P5d9~Fi^brick}g_x?/Rosyb>}khakiSilv9xv[0Indi@0P9uChoco]T@{JT81leOr/G_7v[0Crims4GaQsb?oP2mBurlywood{cy@3}s=V[7g_{c?UKhakiAlice~H4eydewAzu^S@dyb>Wh:tBeigeWXsmokeMQtc^amGho1wXS=AntiquewXLQE{g_yZOldlaceRedM+Deep.Or-0TomatoHot.C?U}?-{s=Or-{.PQkGoldP:chpuffNavaj5XMoccasQBisqueMi1yroseBl@ched=dPapayaw8p3b2shS:shellC?nsilkLem4c8ff4Fl?UwXSn5YZ{yZIv?yWX~b2e}Dark|g^E{LightxMedium`urquoise_oldErod^re]late[ioletZell5X8teUalQinJg^yEen@an?or>r5n=Um4<urple;quamarQe:ea9er8hi7PUe6live5ow4on3LavEd92lu1st0^d/c8d.pQk-@ge,ky~+agEta*prQg|';for(i of'*+,-./0123456789:;<=>?@EJQUXZ[]^_`x{|}~')with(_.split(i))_=join(pop())

f =

c=>(b=document.body,_.match(/.[a-z]*/g).map(t=>getComputedStyle(b,b.style.color=t).color.match(/\d+/g).map((v,i)=>s+=Math.abs((c>>16-8*i&255)-v),s=0)|m>=s&&(m=s,r=t),r=m=c),r)
_='BlackNavy}~x~B2e}|G^ETeU}cy@Deeps,}t`xs*LimeS*Cy@Midnight~Dodg9~{s:GFo^1|S:|}s]JLime|xs:|T`RoyU~Steel~}s]~xt`Indigo}o6|Cadet~C?nfl59~Rebeccap<xa;DimJS]~O6drabS]J{s]Jxs]~Lawn|Chart^useA;Maro4P<O6GrayG^yS,{s,B2ev[}0}m+Saddleb>}s:|{|xp<}v[7|}?/YZ|SiEnaB>}J{~G^EyZ7t`{1eel~P5d9~Fi^brick}g_x?/Rosyb>}khakiSilv9xv[0Indi@0P9uChoco]T@{JT81leOr/G_7v[0Crims4GaQsb?oP2mBurlywood{cy@3}s=V[7g_{c?UKhakiAlice~H4eydewAzu^S@dyb>Wh:tBeigeWXsmokeMQtc^amGho1wXS=AntiquewXLQE{g_yZOldlaceRedM+Deep.Or-0TomatoHot.C?U}?-{s=Or-{.PQkGoldP:chpuffNavaj5XMoccasQBisqueMi1yroseBl@ched=dPapayaw8p3b2shS:shellC?nsilkLem4c8ff4Fl?UwXSn5YZ{yZIv?yWX~b2e}Dark|g^E{LightxMedium`urquoise_oldErod^re]late[ioletZell5X8teUalQinJg^yEen@an?or>r5n=Um4<urple;quamarQe:ea9er8hi7PUe6live5ow4on3LavEd92lu1st0^d/c8d.pQk-@ge,ky~+agEta*prQg|';for(i of'*+,-./0123456789:;<=>?@EJQUXZ[]^_`x{|}~')with(_.split(i))_=join(pop())


console.log(f(0xFF04FE));
console.log(f(0xFFFFFF));
console.log(f(0x457CCB));
document.body.style.color = 'black';

Third JavaScript language in this question now...

getComputedStyle always returns colors in rgb(x, y, z) form if alpha == 1 on Firefox.

_ variable holds the string with all color names in the form BlackNavyDarkblueMediumblueBlueDarkgreen...White.

Save 11 bytes thanks to Kevin Cruijssen by removing unnecessary colors. Save ~350 bytes thanks to Arnauld by introducing some strange packing algorithm.

\$\endgroup\$
6
  • \$\begingroup\$ You should save 350+ bytes by RegPack'ing your string, or maybe the entire code, this time. ;) \$\endgroup\$
    – Arnauld
    Jul 2, 2019 at 11:47
  • \$\begingroup\$ Save a few bytes by assigning document.body to b within getComputedStyle, allowing you to remove the enclosing parentheses. \$\endgroup\$
    – Shaggy
    Jul 2, 2019 at 11:53
  • \$\begingroup\$ FuchsiaMagenta and AquaCyan can both be either of the two instead of both, since they're (just like the Gray/Grey) the same color-codes. \$\endgroup\$ Jul 2, 2019 at 13:17
  • \$\begingroup\$ @Shaggy but the parentheses are still required by ,r maybe \$\endgroup\$
    – tsh
    Jul 3, 2019 at 2:36
  • \$\begingroup\$ @tsh, use &&r instead. \$\endgroup\$
    – Shaggy
    Jul 3, 2019 at 7:59
2
\$\begingroup\$

JavaScript (Node.js) + color-name package, 259 279 284 259 278 282 299 312 364 bytes

c=>{w=[]
K=Object.keys
for(x in d=require('color-name')){(w[W=(p=i=>Math.abs(d[x][2-i]-(255&("0x"+c)>>8*i)))(2)+p(1)+p(0)]=w[W]||[]).push(x)}S=[]
for(s of r=w[K(w)[0]]){(S[z=(W=d[s])[0]+W[1]+W[2]]=S[z]||[]).push([d[s],s])}return S[K(S).pop()].sort().pop()[1]}

Try it online!

Commented:

c=>{w=[]                      // build dict of arrays of names, by color distance:
K=Object.keys
for(x in d=require('color-name')){
  (w[W=
      (p=i=>Math.abs(d[x][2-i]-(255&("0x"+c)>>8*i)))(2) + p(1) +p(0)
    ] = w[W]||[]).push(x)
}S=[]                         // distances were ordered by Object.keys()
for(s of r=w[K(w)[0]]){       // build dict of [[RGB, name]+] by channel sum for distance ties:
  (S[ z= (W=d[s])[0] + W[1] + W[2] ]= S[z]||[]).push([d[s],s])
} return S[ K(S).pop()        // highest channel sum
          ].sort().pop()[1]}  // [name of] highest RGB

I had to

npm install color-name

for the require() to work. I don't think I can npm install on TIO, so I hardcoded the dictionary in the header.

This package contains the same 148 entries as the w3schools page, names are lowercase. I have no idea who created it and when, I just found it while googling. There is a Debian package for it, so I assume it's older than this question.

[Edit: third size reduction / major overhaul]
[Edit 5th/correction: that version had 282 bytes but was missing the tiebreak by RGB value. I don't think I can fix that one and then golf it smaller than this one, so I removed that code from the post.]

This time, I rewrote most of the code. I feel that it's so different from before, it doesn't make sense to keep history in the post.

@Shaggy saved me 4 bytes from the last version by omitting parentheses around single arrow function parameters. Now, there are 6 of those, so basically I owe 12 bytes of thanks.

I switched from constructing dicts/lists manually to using map and filter everywhere, which enabled/prompted a lot of restructuring. I also found some more situations where I could assign variables later.

[Edit: 4th shrinking, return to the roots]

Within a minute of dismissing history (above), I realized my mistake in saying that.
I applied the lessons learned so far to the old code, and I saw that the second sort() was pointless. So right now, that code is ahead by 4 bytes.
[Edit: 4.1th: DUH! all sorts were pointless. -19 more bytes]

[Edit: 5th iteration, growing but now (hopefully) correct]

@Lukas Lang pointed out that my code wasn't correct in cases where the channel sum was tied. I had the wrong impression that this never occurs.
To fix it, I needed to fill the arrays in S with [RGBarray, name] pairs instead of just names. This way, default array sorting completes the job.

[Edit: 6th reduction - gift from a higher realm]

@Shaggy gets all the credit for this round. .reverse()[0] is .pop(). Obviously... Also, implicit type conversion makes ('0x'+c) work instead of parseInt(c,16). And if you get the parantheses right, EVERY variable can be assigned at first use. This time, that was W and p.

\$\endgroup\$
10
  • 12
    \$\begingroup\$ If you have a required package that’s not a standard part of the language, it needs to be in the language header at the top of your entry (i.e. JavaScript (Node.js) + color-name). This means it competes with other entries using the same package, but not directly with other JavaScript (Node.js) entries. \$\endgroup\$ Jul 1, 2019 at 6:07
  • \$\begingroup\$ That makes sense. Thanks! \$\endgroup\$ Jul 1, 2019 at 15:39
  • 3
    \$\begingroup\$ If an arrow function only has one parameter, it does not need to be enclosed in parentheses. \$\endgroup\$
    – Shaggy
    Jul 1, 2019 at 22:47
  • 1
    \$\begingroup\$ Unless I'm mistaken, the code fails for cases where the second tie-breaking rule is needed, such as e8fcf8: both Azure and MintCream have a distance of 18 to that color, and a channel sum of 750. Thus the result should be MintCream, while this code returns Azure. \$\endgroup\$
    – Lukas Lang
    Jul 2, 2019 at 14:29
  • 1
    \$\begingroup\$ A few quick tweaks from my phone: tio.run/… \$\endgroup\$
    – Shaggy
    Jul 2, 2019 at 20:32
1
\$\begingroup\$

05AB1E, 1175 bytes

.•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬ޸%ð°¤]γθγçkÌã©Ð:8•
#`“ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0޹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0ަ0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0ަ0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0ަ0‡—Ê£ÿ s0ަ0°¯¦º0ަ0°¯–ís0ަ0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇݰŠ0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“„0 K#•zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫Â
åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;••O褕в.¥εI‚₄S₁β+₁∦`αO}Wkè

That took quite a while.. 139 colors to create a string of.. >.>

Takes input as a 24-bit integers to save 1 byte.

Try it online or verify a few more test cases. (Both are slightly modified to take Hexadecimal strings as input instead, since it's easier to test.)

Explanation:

First we generate all the color-strings:

.•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬ޸%ð°¤]γθγçkÌã©Ð:8•
                '# Push compressed string "chiffon lavenderblush papayawhip blanchedalmond misty bisque moccasin navajo puff beige azure dew khaki violet lavender cyan burly plum boro crimson violet orchid tle violet khaki rosy orchid turquoise sienna orchid violet dle violet maroon drab cadet indigo turquoise turquoise cyan turquoise steelblue"
  #              # Split this string on spaces
   `             # Push each string separately to the stack
    “ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0޹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0ަ0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0ަ0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0ަ0‡—Ê£ÿ s0ަ0°¯¦º0ަ0°¯–ís0ަ0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇݰŠ0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“
                 # Push dictionary string "black navy dark0 blue medium0 blue blue dark0 green green teal darkÿ deep0 sky0 blue darkÿ medium0 spring0 green lime spring0 green aqua midnight0 blue dodger0 blue light0 sea0 green forest0 green sea0 green darks0 late0 grey lime0 green medium0 sea0 green ÿ royal0 blue steel0 blue darks0 late0 blue mediumÿ ÿ dark0 olive0 green ÿ0 blue corn0 flower0 blue rebecca0 purple medium0 aqua0 marine dim0 grey s0 late0 blue oliveÿ s0 late0 grey lights0 late0 grey mediums0 late0 blue lawn0 green chartre0 use aqua0 marine ÿ purple olive grey sky0 blue light0 sky0 blue blueÿ dark0 red darkm0 agenta sadÿ0 brown dark0 sea0 green light0 green medium0 purple darkÿ pale0 green darkÿ yellow0 green ÿ brown dark0 grey light0 blue green0 yellow paleÿ light0 steel0 blue powder0 blue fire0 brick dark0 golden0 rod mediumÿ ÿ0 brown darkÿ silver mediumÿ0 red indian0 red peru chocolate tan light0 grey thisÿ ÿ golden0 rod paleÿ0 red ÿ gainsÿ ÿ ÿ0 wood lightÿ ÿ dark0 salmon ÿ pale0 golden0 rod light0 coral ÿ alice0 blue honeyÿ ÿ sandy0 brown wheat ÿ white0 smoke mint0 cream ghost0 white salmon antique0 white linen light0 golden0 rod0 yellow old0 lace red m0 agenta deep0 pink orange0 red tomato hot0 pink coral dark0 orange light0 salmon orange light0 pink pink gold p0 eachÿ ÿ0 white ÿ ÿ ÿ0 rose ÿ ÿ ÿ sea0 shell corn0 silk lemonÿ floral0 white snow yellow light0 yellow ivory white"
                 # Where all `ÿ` are automatically filled with the strings on the stack
      „0 K       # Remove all "0 " from this string
          #      # Split the colors on spaces

Then we generate a list of forward differences (deltas) between each integer value of the colors:

•zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫Â
åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;•
                 # Push compressed integer 199435987809271424589508700952987345999804200072375133628254343692108407476588500135573281889031649216370100759626064238727072489415325130552011943231372407222964404763401980843968947657212497212027480199840300219769136432328209307347145119976644138878553798683794751309798787883572249589074597119540397124774131357786254535108429605287982569524294490533853150008626425797260994727581899181000813165364870780739754491720041566206327597753141661846275821649635815830948299823383964329384068145070200611196756567681968774265025511020508722510627341700584849057763591073777679021648285012447092662591008342199952284925672007531443930335828262810273697784303468071652124201899153101970895280421720006686387730894329535589566680885995478455871002071758051626349351150223272343920758114226776399859623393233070539000599481915926111317851112136858026586181791
•O褕            # Push compressed integer 1579378
     в           # Convert the larger integer to Base-1579378 as list: [128,11,66,50,25345,7168,128,2827,13428,3794,11209,1126,127,128,1579377,358287,139691,120952,786485,50168,228835,648767,273759,35089,334035,113367,37953,143030,682669,668529,325453,105900,39441,170943,61796,78678,324205,460809,254037,103186,197376,212,44,128,32640,128,478827,15,154856,54302,139,17544,292732,78337,164427,36856,326341,14132,105062,361723,317437,294783,274237,9801,126911,54768,7176,82236,418793,118728,145852,75740,198997,414917,411351,10467,320479,19310,73543,322565,110846,13386,52083,41897,51360,50177,71594,149368,386811,176000,322676,26044,104406,26124,4723,1777,15,238689,80467,5929,25,2565,194821,100211,27493,1295,2540,195348,68122,255,5012,12397,7751,1645,5532,3248,5242,1158,4545,2570,5685,953,1012,1544,15,29,1772,1032,288,1273,750,497,35,10,1030,224,16,15]
      .¥         # Undelta this list: [0,128,139,205,255,25600,32768,32896,35723,49151,52945,64154,65280,65407,65535,1644912,2003199,2142890,2263842,3050327,3100495,3329330,3978097,4251856,4286945,4620980,4734347,4772300,4915330,5597999,6266528,6591981,6697881,6737322,6908265,6970061,7048739,7372944,7833753,8087790,8190976,8388352,8388564,8388608,8388736,8421376,8421504,8900331,8900346,9055202,9109504,9109643,9127187,9419919,9498256,9662683,9699539,10025880,10040012,10145074,10506797,10824234,11119017,11393254,11403055,11529966,11584734,11591910,11674146,12092939,12211667,12357519,12433259,12632256,13047173,13458524,13468991,13789470,13808780,13882323,14204888,14315734,14329120,14381203,14423100,14474460,14524637,14596231,14745599,15132410,15308410,15631086,15657130,15761536,15787660,15792383,15794160,15794175,16032864,16113331,16119260,16119285,16121850,16316671,16416882,16444375,16445670,16448210,16643558,16711680,16711935,16716947,16729344,16737095,16738740,16744272,16747520,16752762,16753920,16758465,16761035,16766720,16767673,16768685,16770229,16770244,16770273,16772045,16773077,16773365,16774638,16775388,16775885,16775920,16775930,16776960,16777184,16777200,16777215]

Then we determine the index of the value closest to the input (in terms of absolute differences between each RGB color - and here I thought I could use builtin .x..), determine the index of this closest integer in the list, and use that to index into the color-strings we created earlier:

ε                # Map each integer to:
 I‚              #  Pair it with the input-integer
   ₄S            #  Push 1000, split to digits: [1,0,0,0]
     ₁β          #  Converted from base-256 to an integer: 16777216
       +         #  Add that to both integers in the pair
        ₁в       #  Convert both integers to base-256 as list (we now have [1,R,G,B])
          €¦     #  Remove the leading 1
            `    #  Push both lists to the stack
             α   #  Get the absolute difference between the lists (at the same indices)
              O  #  Sum these differences
}W               # After the map: get the minimum (without popping the list itself)
  k              # Get the index of this minimum in the list
   è             # And use it to index into the string-color list
                 # (after which the result is output implicitly)

See this 05AB1E tip of mine (all four sections) to understand why:

  • .•ŒRǝ...Ð:8• is "chiffon lavenderblush papayawhip ... cyan turquoise steelblue"
  • “ƒÏª©–°0‡—...‡Ž0ŠÛ؉„¸“ is "black navy dark0 blue ... light0 yellow ivory white"
  • •zÑÄ...C±;• is 199...791
  • •O褕 is 1579378
  • •zÑÄ...C±;••O褕в is [128,11,66,...,224,16,15]
\$\endgroup\$
3
  • 1
    \$\begingroup\$ That. Is the longest 05AB1E program. I have ever seen. \$\endgroup\$
    – moltarze
    Jul 2, 2019 at 23:15
  • \$\begingroup\$ @connectyourcharger Yep, by far the largest I've written, beating my previous largest program of 176 bytes.. xD Not really something to be proud of with a code-golfing challenge, though. ;) \$\endgroup\$ Jul 3, 2019 at 6:33
  • 1
    \$\begingroup\$ You earned my upvote though :) \$\endgroup\$
    – moltarze
    Jul 3, 2019 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.