title: What colour is this?

text:
# Question
Title: What colour is this?
Given three number values - being the Red, Green, and Blue elements of a colour (eight bits per channel, 0 to 255) - your program must output the **name** of the given colour.

For example;

```
Input:  255, 0, 0
Output: Red

```

or;

```
Input:  80, 0, 0
Output: Dark Red

```

This is a popularity contest, so whichever answer has the most votes by the first of July wins.

Ispired by: Show the input RGB color

# Answer
> 125 votes
# Python

This is a Python script that uses the results from xkcd's Color Survey, in which Randall Munroe asked thousands of people the exact same question. He arrived at the following chart:

The survey only has data on fully-saturated colors (I guess non-saturated colors would all be described as 'grayish'). This means we have to do some color-related tricks to force our input to become fully saturated.

What I've done here is just convert the input color to HSV, crank up the saturation, and call it a day. This is probably not very correct from a color perception point of view, but it works well enough here - and it's simple enough that you only need the standard library. Batteries included indeed.

The script expects satfaces.txt, from here (mirror), to be in the current directory.

```
import sys, colorsys

n = (int(sys.argv[1], 16))
r = ((n & 0xff0000) >> 16) / 255.0
g = ((n & 0x00ff00) >> 8) / 255.0
b = ((n & 0x0000ff)) / 255.0

(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
(r, g, b) = colorsys.hsv_to_rgb(h, 1, v)

match = "[{}, {}, {}]".format(int(r*255), int(g*255), int(b*255))

for line in open("satfaces.txt"):
    if line.startswith(match):
        print("You were thinking of: " + line.split("] ")[1].strip())
        break

```

Some example runs:

```
$ python color.py CEB301
You were thinking of: yellow
$ python color.py CC9900
You were thinking of: orange
$ python color.py CC0000
You were thinking of: red
$ python color.py 0077FF
You were thinking of: blue

```

And here are the colors:

I'd say that's pretty close.

# Answer
> 91 votes
## Update with GUI!

I take the color list from this Wikipedia page (and the related pages).

I also included some NLG to produce results like "Bulgarian Rose with slightly less green and blue" and some variants of it. Try to play along to see whether you can guess the true "Bulgarian Rose" using those feedbacks. :)

The algorithm will try to find the color which is the closest to the input, as defined by the Euclidean distance. So you can input any number triplet and it will give the color which is the closest to that triplet.

(the code accepts "comma-space separated", "space separated", or "comma separated" values)

### Warning

This code connects to Wikipedia, and so it requires Internet connection in order to run the first time (and write the information in a file in the same dictionary). The subsequent times, though, it will read from file. If you want the offline version, the code is available at this Ideone link (with sample run).

Code:

```
import re, os
from bs4 import BeautifulSoup as BS
import requests
import cPickle as pickle
import random

def encode_color(text):
    return tuple(map(int, re.split(', |,| ', text)))

def color_name(col):
    global color_map, color_nums
    arr = color_nums
    closest = None
    min_dist = 10**8
    for color in arr:
        dist = sum((color[i]-col[i])**2 for i in range(3))
        if dist < min_dist:
            closest = color
            min_dist = dist
    result = color_map[closest]
    rgb = ['red', 'green', 'blue']
    slightly_more = ['with a hint of', 'with traces of', 'with slightly more']
    slightly_less = ['with subdued', 'with slightly less']
    more_more = ['with more', 'with strong hint of']
    more_less = ['with less', 'with diminished']
    count = 0
    adds = ['','']
    for i in range(3):
        expl_list = ['']
        if 5 < col[i]-closest[i] < 10:
            expl_list = slightly_more
            count += 1
            add_idx = 0
        elif 10 <= col[i]-closest[i]:
            expl_list = more_more
            count += 2
            add_idx = 0
        elif -10 <= col[i]-closest[i] < -5:
            expl_list = slightly_less
            count -= 1
            add_idx = 1
        elif col[i]-closest[i] <= -10:
            expl_list = more_less
            count -= 2
            add_idx = 1
        expl = expl_list[random.randint(0, len(expl_list)-1)]
        if expl is not '':
            if adds[add_idx] is '':
                adds[add_idx] += ' %s %s' % (expl, rgb[i])
            else:
                adds[add_idx] += ' and %s' % rgb[i]
    if 3 <= count <= 4:
        result = 'A slightly brighter '+result
    elif 4 < count:
        result = 'A brighter '+result
    elif -4 <= count <= -3:
        result = 'A slightly darker '+result
    elif count < -4:
        result = 'A darker '+result
    elif count > 0:
        result += adds[0]
    elif count < 0:
        result += adds[1]
    return result

links = ['http://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F',
         'http://en.wikipedia.org/wiki/List_of_colors:_G%E2%80%93M',
         'http://en.wikipedia.org/wiki/List_of_colors:_N%E2%80%93Z']

def is_color(tag):
    return tag.name == 'th' and len(tag.contents)==1 and tag.contents[0].name=='a'

def parse_color(hexa):
    return (int(hexa[0:2], 16), int(hexa[2:4], 16), int(hexa[4:6], 16))

print 'Loading color names...'
if os.path.exists('parse_wiki_color.pickle'):
    with open('parse_wiki_color.pickle', 'rb') as infile:
        color_map, color_nums = pickle.load(infile)
else:
    color_map = {}
    color_nums = []
    for link in links:
        soup = BS(requests.get(link).text,'lxml')
        for color in soup.find_all(is_color):
            try:
                color_num = parse_color(color.next_sibling.next_sibling.string[1:])
                color_nums.append(color_num)
                color_map[color_num] = str(color.a.string)
            except:
                continue
    color_nums = sorted(color_nums)
    with open('parse_wiki_color.pickle', 'wb') as outfile:
        pickle.dump((color_map, color_nums), outfile, protocol=2)
print 'Color names loaded'

def main(event=None):
    global var, col_name, col_disp
    text = var.get()
    color = encode_color(text)
    result = color_name(color)
    col_name.set(result)
    col_rgb.set(color)
    var.set('')
    col_disp.configure(background='#%02x%02x%02x' % color)

from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
caption = Label(frame, text='Enter RGB color:')
caption.pack(side=LEFT)
var = StringVar()
entry = Entry(frame, textvariable=var)
entry.focus_set()
entry.pack(side=LEFT)
entry.bind('<Return>',func=main)
button = Button(frame, text='Get name', command=main)
button.pack(side=LEFT)
col_rgb = StringVar()
col_rgb_disp = Label(root, textvariable=col_rgb)
col_rgb_disp.pack()
col_name = StringVar()
col_label = Label(root, textvariable=col_name)
col_label.pack()
col_disp = Label(root)
col_disp.configure(padx=50, pady=45, relief=RAISED)
col_disp.pack()
root.geometry('400x200')
root.mainloop()

```

# Answer
> 77 votes
### JavaScript

The following function is written with canine users in mind:

```
function getColorName(r, g, b) {
    return "gray";
}

```

For the more refined dogs out there:

```
function getColorName(r, g, b) {
    var gray = (0.21*r + 0.71*g + 0.07*b);
    if (gray < 64)
        return "black";
    else if (gray < 128)
        return "dark gray";
    else if (gray < 192)
        return "light gray";
    else if (gray < 256)
        return "white";
    else
        whimper();
}

```

# Answer
> 43 votes
# Javascript

```
window.location = 'http://www.color-hex.com/color/' + 'ff00ff'

```

# Answer
> 34 votes
# Mathematica

Update: Added a parameter for setting the number of closest colors to display. The default is 5 colors.

Given the RGB values of an unnamed color, the following finds the `n` nearest colors from a list of 140 HTML color names. It then plots the unnamed color and its 5 nearest neighbors in a 3-space, with axes for Red, Green, and Blue. In the plot label it names the nearest color and provides its RGB values.

```
colorInterpret[rgb_,n_: 5]:=
Module[{colorData,valsRGB,pts,closest},
colorData=({ColorData["HTML",#],#}&/@ColorData["HTML","Range"][[1]])/.{RGBColor[x__]:> {x}};
valsRGB=colorData[[All,1]];
pts=Append[colorData[[Position[valsRGB,#]&/@Nearest[valsRGB,rgb,n]//Flatten]],{rgb,"Unnamed Color"}];
closest=pts[[1]];
Graphics3D[{PointSize[.05],
{RGBColor@@#,Point[#],Text[Style[#2,Black,14],(#-{.01,.01,.01})]}&@@@pts
},
Axes-> True,
PlotLabel-> Row[{"closest color: ", closest}],
ImageSize-> 600,
ImagePadding-> 50,
BaseStyle-> 14,
AxesLabel->{Style["Red",18],Style["Green",18],Style["Blue",18]}]]

```

**Examples**

Display the 5 closest colors:

```
 colorInterpret[{.55, .86, .69}]

```

---

Display the 15 closest colors:

# Answer
> 27 votes
# CJam

```
l~]:X;"xkcd.com/color/rgb.txt"gN%"  "f%{[1=1>eu2/{:~Gb}%X]z{:-}%2f#:+}$0=0=

```

This gets the list of colors from xkcd and finds the nearest one.
Note: the space-looking string in the middle is actually one tab.

To run it, please use the interpreter from http://sf.net/p/cjam

**Example:**

Input `147 125 0`
Output `baby poop`

# Answer
> 18 votes
## R

R has an embedded list of 657 color names for plotting purposes. The following code take input from user, and computes the distance between this rgb input and the rgb value of those 657 colors and outputs the name of the closest one.

```
a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a)))))

```

Ungolfed:

```
a <- as.integer(strsplit(readline(),", ")[[1]]) #Ask user input as stdin, and process it
color_list <- sapply(colors(),col2rgb) #Convert the color name list into an RGB matrix
#Computes the difference with user input, adds the absolute value and output the name of the element with the minimal value
names(which.min(colSums(abs(apply(color_list, 2, function(x)x-a)))))

```

Examples:

```
> a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a)))))
80, 0, 2
[1] "darkred"
> a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a)))))
150, 150, 150
[1] "gray59"
> a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a)))))
0, 200, 255
[1] "deepskyblue"
> a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a)))))
255, 100, 70
[1] "tomato"

```

**Edit:** Same idea but using the list of name from colorHexa:

```
a=strsplit(xpathSApply(htmlParse("http://www.colorhexa.com/color-names"),"//li",xmlValue),"#")
n=sapply(a,`[`,1)
r=apply(do.call(rbind,strsplit(sapply(a,`[`,2)," "))[,2:4],2,as.integer)
n[which.min(colSums(abs(apply(r,1,`-`,as.integer(strsplit(readline(),", ")[[1]])))))]

```

Example:

```
> a=strsplit(xpathSApply(htmlParse("http://www.colorhexa.com/color-names"),"//li",xmlValue),"#")
> n=sapply(a,`[`,1)
> r=apply(do.call(rbind,strsplit(sapply(a,`[`,2)," "))[,2:4],2,as.integer)
> n[which.min(colSums(abs(apply(r,1,`-`,as.integer(strsplit(readline(),", ")[[1]])))))]
208, 32, 12
[1] " Fire engine red "

```

# Answer
> 11 votes
# Perl

Expects `http://xkcd.com/color/rgb.txt` in current directory. Displays five closest colours with nice percentage.

## Example run

```
> perl code.pl
147,125,0
99.87% baby poop
98.44% yellowish brown
98.31% puke brown
97.79% poo
97.27% diarrhea

```

## Code

```
#!perl -w
use strict;

sub hex2rgb ($) {
    my ($h) = @_;
    map {hex} ($h=~/[0-9a-fA-F]{2}/g)
}

sub distance ($$) {
    my ($acol1, $acol2) = @_;
    my $r = 0;
    $r += abs($acol1->[$_] - $acol2->[$_]) for (0..$#$acol1);
    $r
}

sub read_rgb {
    open my $rgb, '<', 'rgb.txt' or die $!;
    my @col;
    while (<$rgb>) {
    my ($name, $hex) = split /\t#/;
    my @rgb = hex2rgb $hex;
    push @col, [@rgb, $name];
    }
    close $rgb;
    \@col
}

my $acolours = read_rgb;
my @C = split /, */, <>;

printf "%.02f%% %s\n", (768-$_->[0])/768*100, $_->[4] for
    (sort {$a->[0] <=> $b->[0]}
     map [distance(\@C, $_), @$_], @$acolours)[0..4];

```

# Answer
> 10 votes
# Scala

My attempt — the killer feature is that it doesn't require Internet connection! (I hope it's not too long :D ) Also, I did summon Chtulhu while preparing color database (because I parsed a subset of HTML with regex; the regex and the link to source are in comments)

Edit: improved accuracy

Example run: http://ideone.com/e3n0dG

```
object Main {

  def main(args: Array[String]) {
    val color = extractBrightness(readLine().split("[, ]+").map(_.toInt))

    val nearestColor = colors.minBy(t => distance(extractBrightness(parseColor(t._1)), color, weight))._2
    println(s"Your color is $nearestColor")
  }

  def parseColor(s: String) = {
    s.sliding(2, 2).map(Integer.parseInt(_, 16)).toVector
  }

  def distance(c1: Seq[Double], c2: Seq[Double], weight: Seq[Double]) = {
    c1.zip(c2).map(t => ((x: Double) => x * x)(t._1 - t._2)).zip(weight).map(t => t._1 * t._2).sum
  }

  val weight = Vector(0.01, 1.0, 0.8)

  def extractBrightness(c: Seq[Int]) = {
    val Seq(r, g, b) = c
    val brightness = c.sum.toDouble / 3
    val rOffset = r - brightness
    val bOffset = b - brightness
    Seq(brightness, rOffset, bOffset)
  }

  // colors are extracted by using this regex:
[\s\S]*?([\w ]+)[\s\S]*?#(......)[\s\S]*?

  // from this page: http://www.colorhexa.com/color-names
  val colors = Vector(
    "5d8aa8" -> "Air Force blue",
    "f0f8ff" -> "Alice blue",
    "e32636" -> "Alizarin crimson",
    "efdecd" -> "Almond",
    "e52b50" -> "Amaranth",
    "ffbf00" -> "Amber",
    "ff033e" -> "American rose",
    "9966cc" -> "Amethyst",
    "a4c639" -> "Android Green",
    "cd9575" -> "Antique brass",
    "915c83" -> "Antique fuchsia",
    "faebd7" -> "Antique white",
    "008000" -> "Ao",
    "8db600" -> "Apple green",
    "fbceb1" -> "Apricot",
    "00ffff" -> "Aqua",
    "7fffd4" -> "Aquamarine",
    "4b5320" -> "Army green",
    "e9d66b" -> "Arylide yellow",
    "b2beb5" -> "Ash grey",
    "87a96b" -> "Asparagus",
    "ff9966" -> "Atomic tangerine",
    "a52a2a" -> "Auburn",
    "fdee00" -> "Aureolin",
    "6e7f80" -> "AuroMetalSaurus",
    "ff2052" -> "Awesome",
    "007fff" -> "Azure",
    "89cff0" -> "Baby blue",
    "a1caf1" -> "Baby blue eyes",
    "f4c2c2" -> "Baby pink",
    "21abcd" -> "Ball Blue",
    "fae7b5" -> "Banana Mania",
    "ffe135" -> "Banana yellow",
    "848482" -> "Battleship grey",
    "98777b" -> "Bazaar",
    "bcd4e6" -> "Beau blue",
    "9f8170" -> "Beaver",
    "f5f5dc" -> "Beige",
    "ffe4c4" -> "Bisque",
    "3d2b1f" -> "Bistre",
    "fe6f5e" -> "Bittersweet",
    "000000" -> "Black",
    "ffebcd" -> "Blanched Almond",
    "318ce7" -> "Bleu de France",
    "ace5ee" -> "Blizzard Blue",
    "faf0be" -> "Blond",
    "0000ff" -> "Blue",
    "a2a2d0" -> "Blue Bell",
    "6699cc" -> "Blue Gray",
    "0d98ba" -> "Blue green",
    "8a2be2" -> "Blue purple",
    "8a2be2" -> "Blue violet",
    "de5d83" -> "Blush",
    "79443b" -> "Bole",
    "0095b6" -> "Bondi blue",
    "e3dac9" -> "Bone",
    "cc0000" -> "Boston University Red",
    "006a4e" -> "Bottle green",
    "873260" -> "Boysenberry",
    "0070ff" -> "Brandeis blue",
    "b5a642" -> "Brass",
    "cb4154" -> "Brick red",
    "1dacd6" -> "Bright cerulean",
    "66ff00" -> "Bright green",
    "bf94e4" -> "Bright lavender",
    "c32148" -> "Bright maroon",
    "ff007f" -> "Bright pink",
    "08e8de" -> "Bright turquoise",
    "d19fe8" -> "Bright ube",
    "f4bbff" -> "Brilliant lavender",
    "ff55a3" -> "Brilliant rose",
    "fb607f" -> "Brink pink",
    "004225" -> "British racing green",
    "cd7f32" -> "Bronze",
    "a52a2a" -> "Brown",
    "ffc1cc" -> "Bubble gum",
    "e7feff" -> "Bubbles",
    "f0dc82" -> "Buff",
    "480607" -> "Bulgarian rose",
    "800020" -> "Burgundy",
    "deb887" -> "Burlywood",
    "cc5500" -> "Burnt orange",
    "e97451" -> "Burnt sienna",
    "8a3324" -> "Burnt umber",
    "bd33a4" -> "Byzantine",
    "702963" -> "Byzantium",
    "007aa5" -> "CG Blue",
    "e03c31" -> "CG Red",
    "536872" -> "Cadet",
    "5f9ea0" -> "Cadet blue",
    "91a3b0" -> "Cadet grey",
    "006b3c" -> "Cadmium green",
    "ed872d" -> "Cadmium orange",
    "e30022" -> "Cadmium red",
    "fff600" -> "Cadmium yellow",
    "a67b5b" -> "Café au lait",
    "4b3621" -> "Café noir",
    "1e4d2b" -> "Cal Poly Pomona green",
    "a3c1ad" -> "Cambridge Blue",
    "c19a6b" -> "Camel",
    "78866b" -> "Camouflage green",
    "ffff99" -> "Canary",
    "ffef00" -> "Canary yellow",
    "ff0800" -> "Candy apple red",
    "e4717a" -> "Candy pink",
    "00bfff" -> "Capri",
    "592720" -> "Caput mortuum",
    "c41e3a" -> "Cardinal",
    "00cc99" -> "Caribbean green",
    "ff0040" -> "Carmine",
    "eb4c42" -> "Carmine pink",
    "ff0038" -> "Carmine red",
    "ffa6c9" -> "Carnation pink",
    "b31b1b" -> "Carnelian",
    "99badd" -> "Carolina blue",
    "ed9121" -> "Carrot orange",
    "ace1af" -> "Celadon",
    "b2ffff" -> "Celeste",
    "4997d0" -> "Celestial blue",
    "de3163" -> "Cerise",
    "ec3b83" -> "Cerise pink",
    "007ba7" -> "Cerulean",
    "2a52be" -> "Cerulean blue",
    "a0785a" -> "Chamoisee",
    "fad6a5" -> "Champagne",
    "36454f" -> "Charcoal",
    "7fff00" -> "Chartreuse",
    "de3163" -> "Cherry",
    "ffb7c5" -> "Cherry blossom pink",
    "cd5c5c" -> "Chestnut",
    "d2691e" -> "Chocolate",
    "ffa700" -> "Chrome yellow",
    "98817b" -> "Cinereous",
    "e34234" -> "Cinnabar",
    "d2691e" -> "Cinnamon",
    "e4d00a" -> "Citrine",
    "fbcce7" -> "Classic rose",
    "0047ab" -> "Cobalt",
    "d2691e" -> "Cocoa brown",
    "6f4e37" -> "Coffee",
    "9bddff" -> "Columbia blue",
    "002e63" -> "Cool black",
    "8c92ac" -> "Cool grey",
    "b87333" -> "Copper",
    "996666" -> "Copper rose",
    "ff3800" -> "Coquelicot",
    "ff7f50" -> "Coral",
    "f88379" -> "Coral pink",
    "ff4040" -> "Coral red",
    "893f45" -> "Cordovan",
    "fbec5d" -> "Corn",
    "b31b1b" -> "Cornell Red",
    "9aceeb" -> "Cornflower",
    "6495ed" -> "Cornflower blue",
    "fff8dc" -> "Cornsilk",
    "fff8e7" -> "Cosmic latte",
    "ffbcd9" -> "Cotton candy",
    "fffdd0" -> "Cream",
    "dc143c" -> "Crimson",
    "990000" -> "Crimson Red",
    "be0032" -> "Crimson glory",
    "00ffff" -> "Cyan",
    "ffff31" -> "Daffodil",
    "f0e130" -> "Dandelion",
    "00008b" -> "Dark blue",
    "654321" -> "Dark brown",
    "5d3954" -> "Dark byzantium",
    "a40000" -> "Dark candy apple red",
    "08457e" -> "Dark cerulean",
    "986960" -> "Dark chestnut",
    "cd5b45" -> "Dark coral",
    "008b8b" -> "Dark cyan",
    "536878" -> "Dark electric blue",
    "b8860b" -> "Dark goldenrod",
    "a9a9a9" -> "Dark gray",
    "013220" -> "Dark green",
    "1a2421" -> "Dark jungle green",
    "bdb76b" -> "Dark khaki",
    "483c32" -> "Dark lava",
    "734f96" -> "Dark lavender",
    "8b008b" -> "Dark magenta",
    "003366" -> "Dark midnight blue",
    "556b2f" -> "Dark olive green",
    "ff8c00" -> "Dark orange",
    "9932cc" -> "Dark orchid",
    "779ecb" -> "Dark pastel blue",
    "03c03c" -> "Dark pastel green",
    "966fd6" -> "Dark pastel purple",
    "c23b22" -> "Dark pastel red",
    "e75480" -> "Dark pink",
    "003399" -> "Dark powder blue",
    "872657" -> "Dark raspberry",
    "8b0000" -> "Dark red",
    "e9967a" -> "Dark salmon",
    "560319" -> "Dark scarlet",
    "8fbc8f" -> "Dark sea green",
    "3c1414" -> "Dark sienna",
    "483d8b" -> "Dark slate blue",
    "2f4f4f" -> "Dark slate gray",
    "177245" -> "Dark spring green",
    "918151" -> "Dark tan",
    "ffa812" -> "Dark tangerine",
    "483c32" -> "Dark taupe",
    "cc4e5c" -> "Dark terra cotta",
    "00ced1" -> "Dark turquoise",
    "9400d3" -> "Dark violet",
    "00693e" -> "Dartmouth green",
    "555555" -> "Davy grey",
    "d70a53" -> "Debian red",
    "a9203e" -> "Deep carmine",
    "ef3038" -> "Deep carmine pink",
    "e9692c" -> "Deep carrot orange",
    "da3287" -> "Deep cerise",
    "fad6a5" -> "Deep champagne",
    "b94e48" -> "Deep chestnut",
    "704241" -> "Deep coffee",
    "c154c1" -> "Deep fuchsia",
    "004b49" -> "Deep jungle green",
    "9955bb" -> "Deep lilac",
    "cc00cc" -> "Deep magenta",
    "ffcba4" -> "Deep peach",
    "ff1493" -> "Deep pink",
    "ff9933" -> "Deep saffron",
    "00bfff" -> "Deep sky blue",
    "1560bd" -> "Denim",
    "c19a6b" -> "Desert",
    "edc9af" -> "Desert sand",
    "696969" -> "Dim gray",
    "1e90ff" -> "Dodger blue",
    "d71868" -> "Dogwood rose",
    "85bb65" -> "Dollar bill",
    "967117" -> "Drab",
    "00009c" -> "Duke blue",
    "e1a95f" -> "Earth yellow",
    "c2b280" -> "Ecru",
    "614051" -> "Eggplant",
    "f0ead6" -> "Eggshell",
    "1034a6" -> "Egyptian blue",
    "7df9ff" -> "Electric blue",
    "ff003f" -> "Electric crimson",
    "00ffff" -> "Electric cyan",
    "00ff00" -> "Electric green",
    "6f00ff" -> "Electric indigo",
    "f4bbff" -> "Electric lavender",
    "ccff00" -> "Electric lime",
    "bf00ff" -> "Electric purple",
    "3f00ff" -> "Electric ultramarine",
    "8f00ff" -> "Electric violet",
    "ffff00" -> "Electric yellow",
    "50c878" -> "Emerald",
    "96c8a2" -> "Eton blue",
    "c19a6b" -> "Fallow",
    "801818" -> "Falu red",
    "ff00ff" -> "Famous",
    "b53389" -> "Fandango",
    "f400a1" -> "Fashion fuchsia",
    "e5aa70" -> "Fawn",
    "4d5d53" -> "Feldgrau",
    "71bc78" -> "Fern",
    "4f7942" -> "Fern green",
    "ff2800" -> "Ferrari Red",
    "6c541e" -> "Field drab",
    "ce2029" -> "Fire engine red",
    "b22222" -> "Firebrick",
    "e25822" -> "Flame",
    "fc8eac" -> "Flamingo pink",
    "f7e98e" -> "Flavescent",
    "eedc82" -> "Flax",
    "fffaf0" -> "Floral white",
    "ffbf00" -> "Fluorescent orange",
    "ff1493" -> "Fluorescent pink",
    "ccff00" -> "Fluorescent yellow",
    "ff004f" -> "Folly",
    "228b22" -> "Forest green",
    "a67b5b" -> "French beige",
    "0072bb" -> "French blue",
    "86608e" -> "French lilac",
    "f64a8a" -> "French rose",
    "ff00ff" -> "Fuchsia",
    "ff77ff" -> "Fuchsia pink",
    "e48400" -> "Fulvous",
    "cc6666" -> "Fuzzy Wuzzy",
    "dcdcdc" -> "Gainsboro",
    "e49b0f" -> "Gamboge",
    "f8f8ff" -> "Ghost white",
    "b06500" -> "Ginger",
    "6082b6" -> "Glaucous",
    "e6e8fa" -> "Glitter",
    "ffd700" -> "Gold",
    "996515" -> "Golden brown",
    "fcc200" -> "Golden poppy",
    "ffdf00" -> "Golden yellow",
    "daa520" -> "Goldenrod",
    "a8e4a0" -> "Granny Smith Apple",
    "808080" -> "Gray",
    "465945" -> "Gray asparagus",
    "00ff00" -> "Green",
    "1164b4" -> "Green Blue",
    "adff2f" -> "Green yellow",
    "a99a86" -> "Grullo",
    "00ff7f" -> "Guppie green",
    "663854" -> "Halayà úbe",
    "446ccf" -> "Han blue",
    "5218fa" -> "Han purple",
    "e9d66b" -> "Hansa yellow",
    "3fff00" -> "Harlequin",
    "c90016" -> "Harvard crimson",
    "da9100" -> "Harvest Gold",
    "808000" -> "Heart Gold",
    "df73ff" -> "Heliotrope",
    "f400a1" -> "Hollywood cerise",
    "f0fff0" -> "Honeydew",
    "49796b" -> "Hooker green",
    "ff1dce" -> "Hot magenta",
    "ff69b4" -> "Hot pink",
    "355e3b" -> "Hunter green",
    "fcf75e" -> "Icterine",
    "b2ec5d" -> "Inchworm",
    "138808" -> "India green",
    "cd5c5c" -> "Indian red",
    "e3a857" -> "Indian yellow",
    "4b0082" -> "Indigo",
    "002fa7" -> "International Klein Blue",
    "ff4f00" -> "International orange",
    "5a4fcf" -> "Iris",
    "f4f0ec" -> "Isabelline",
    "009000" -> "Islamic green",
    "fffff0" -> "Ivory",
    "00a86b" -> "Jade",
    "f8de7e" -> "Jasmine",
    "d73b3e" -> "Jasper",
    "a50b5e" -> "Jazzberry jam",
    "fada5e" -> "Jonquil",
    "bdda57" -> "June bud",
    "29ab87" -> "Jungle green",
    "e8000d" -> "KU Crimson",
    "4cbb17" -> "Kelly green",
    "c3b091" -> "Khaki",
    "087830" -> "La Salle Green",
    "d6cadd" -> "Languid lavender",
    "26619c" -> "Lapis lazuli",
    "fefe22" -> "Laser Lemon",
    "a9ba9d" -> "Laurel green",
    "cf1020" -> "Lava",
    "e6e6fa" -> "Lavender",
    "ccccff" -> "Lavender blue",
    "fff0f5" -> "Lavender blush",
    "c4c3d0" -> "Lavender gray",
    "9457eb" -> "Lavender indigo",
    "ee82ee" -> "Lavender magenta",
    "e6e6fa" -> "Lavender mist",
    "fbaed2" -> "Lavender pink",
    "967bb6" -> "Lavender purple",
    "fba0e3" -> "Lavender rose",
    "7cfc00" -> "Lawn green",
    "fff700" -> "Lemon",
    "fff44f" -> "Lemon Yellow",
    "fffacd" -> "Lemon chiffon",
    "bfff00" -> "Lemon lime",
    "f56991" -> "Light Crimson",
    "e68fac" -> "Light Thulian pink",
    "fdd5b1" -> "Light apricot",
    "add8e6" -> "Light blue",
    "b5651d" -> "Light brown",
    "e66771" -> "Light carmine pink",
    "f08080" -> "Light coral",
    "93ccea" -> "Light cornflower blue",
    "e0ffff" -> "Light cyan",
    "f984ef" -> "Light fuchsia pink",
    "fafad2" -> "Light goldenrod yellow",
    "d3d3d3" -> "Light gray",
    "90ee90" -> "Light green",
    "f0e68c" -> "Light khaki",
    "b19cd9" -> "Light pastel purple",
    "ffb6c1" -> "Light pink",
    "ffa07a" -> "Light salmon",
    "ff9999" -> "Light salmon pink",
    "20b2aa" -> "Light sea green",
    "87cefa" -> "Light sky blue",
    "778899" -> "Light slate gray",
    "b38b6d" -> "Light taupe",
    "ffffed" -> "Light yellow",
    "c8a2c8" -> "Lilac",
    "bfff00" -> "Lime",
    "32cd32" -> "Lime green",
    "195905" -> "Lincoln green",
    "faf0e6" -> "Linen",
    "c19a6b" -> "Lion",
    "534b4f" -> "Liver",
    "e62020" -> "Lust",
    "18453b" -> "MSU Green",
    "ffbd88" -> "Macaroni and Cheese",
    "ff00ff" -> "Magenta",
    "aaf0d1" -> "Magic mint",
    "f8f4ff" -> "Magnolia",
    "c04000" -> "Mahogany",
    "fbec5d" -> "Maize",
    "6050dc" -> "Majorelle Blue",
    "0bda51" -> "Malachite",
    "979aaa" -> "Manatee",
    "ff8243" -> "Mango Tango",
    "74c365" -> "Mantis",
    "800000" -> "Maroon",
    "e0b0ff" -> "Mauve",
    "915f6d" -> "Mauve taupe",
    "ef98aa" -> "Mauvelous",
    "73c2fb" -> "Maya blue",
    "e5b73b" -> "Meat brown",
    "0067a5" -> "Medium Persian blue",
    "66ddaa" -> "Medium aquamarine",
    "0000cd" -> "Medium blue",
    "e2062c" -> "Medium candy apple red",
    "af4035" -> "Medium carmine",
    "f3e5ab" -> "Medium champagne",
    "035096" -> "Medium electric blue",
    "1c352d" -> "Medium jungle green",
    "dda0dd" -> "Medium lavender magenta",
    "ba55d3" -> "Medium orchid",
    "9370db" -> "Medium purple",
    "bb3385" -> "Medium red violet",
    "3cb371" -> "Medium sea green",
    "7b68ee" -> "Medium slate blue",
    "c9dc87" -> "Medium spring bud",
    "00fa9a" -> "Medium spring green",
    "674c47" -> "Medium taupe",
    "0054b4" -> "Medium teal blue",
    "48d1cc" -> "Medium turquoise",
    "c71585" -> "Medium violet red",
    "fdbcb4" -> "Melon",
    "191970" -> "Midnight blue",
    "004953" -> "Midnight green",
    "ffc40c" -> "Mikado yellow",
    "3eb489" -> "Mint",
    "f5fffa" -> "Mint cream",
    "98ff98" -> "Mint green",
    "ffe4e1" -> "Misty rose",
    "faebd7" -> "Moccasin",
    "967117" -> "Mode beige",
    "73a9c2" -> "Moonstone blue",
    "ae0c00" -> "Mordant red 19",
    "addfad" -> "Moss green",
    "30ba8f" -> "Mountain Meadow",
    "997a8d" -> "Mountbatten pink",
    "c54b8c" -> "Mulberry",
    "f2f3f4" -> "Munsell",
    "ffdb58" -> "Mustard",
    "21421e" -> "Myrtle",
    "f6adc6" -> "Nadeshiko pink",
    "2a8000" -> "Napier green",
    "fada5e" -> "Naples yellow",
    "ffdead" -> "Navajo white",
    "000080" -> "Navy blue",
    "ffa343" -> "Neon Carrot",
    "fe59c2" -> "Neon fuchsia",
    "39ff14" -> "Neon green",
    "059033" -> "North Texas Green",
    "0077be" -> "Ocean Boat Blue",
    "cc7722" -> "Ochre",
    "008000" -> "Office green",
    "cfb53b" -> "Old gold",
    "fdf5e6" -> "Old lace",
    "796878" -> "Old lavender",
    "673147" -> "Old mauve",
    "c08081" -> "Old rose",
    "808000" -> "Olive",
    "6b8e23" -> "Olive Drab",
    "bab86c" -> "Olive Green",
    "9ab973" -> "Olivine",
    "0f0f0f" -> "Onyx",
    "b784a7" -> "Opera mauve",
    "ffa500" -> "Orange",
    "f8d568" -> "Orange Yellow",
    "ff9f00" -> "Orange peel",
    "ff4500" -> "Orange red",
    "da70d6" -> "Orchid",
    "654321" -> "Otter brown",
    "414a4c" -> "Outer Space",
    "ff6e4a" -> "Outrageous Orange",
    "002147" -> "Oxford Blue",
    "1ca9c9" -> "Pacific Blue",
    "006600" -> "Pakistan green",
    "273be2" -> "Palatinate blue",
    "682860" -> "Palatinate purple",
    "bcd4e6" -> "Pale aqua",
    "afeeee" -> "Pale blue",
    "987654" -> "Pale brown",
    "af4035" -> "Pale carmine",
    "9bc4e2" -> "Pale cerulean",
    "ddadaf" -> "Pale chestnut",
    "da8a67" -> "Pale copper",
    "abcdef" -> "Pale cornflower blue",
    "e6be8a" -> "Pale gold",
    "eee8aa" -> "Pale goldenrod",
    "98fb98" -> "Pale green",
    "dcd0ff" -> "Pale lavender",
    "f984e5" -> "Pale magenta",
    "fadadd" -> "Pale pink",
    "dda0dd" -> "Pale plum",
    "db7093" -> "Pale red violet",
    "96ded1" -> "Pale robin egg blue",
    "c9c0bb" -> "Pale silver",
    "ecebbd" -> "Pale spring bud",
    "bc987e" -> "Pale taupe",
    "db7093" -> "Pale violet red",
    "78184a" -> "Pansy purple",
    "ffefd5" -> "Papaya whip",
    "50c878" -> "Paris Green",
    "aec6cf" -> "Pastel blue",
    "836953" -> "Pastel brown",
    "cfcfc4" -> "Pastel gray",
    "77dd77" -> "Pastel green",
    "f49ac2" -> "Pastel magenta",
    "ffb347" -> "Pastel orange",
    "ffd1dc" -> "Pastel pink",
    "b39eb5" -> "Pastel purple",
    "ff6961" -> "Pastel red",
    "cb99c9" -> "Pastel violet",
    "fdfd96" -> "Pastel yellow",
    "800080" -> "Patriarch",
    "536878" -> "Payne grey",
    "ffe5b4" -> "Peach",
    "ffdab9" -> "Peach puff",
    "fadfad" -> "Peach yellow",
    "d1e231" -> "Pear",
    "eae0c8" -> "Pearl",
    "88d8c0" -> "Pearl Aqua",
    "e6e200" -> "Peridot",
    "ccccff" -> "Periwinkle",
    "1c39bb" -> "Persian blue",
    "32127a" -> "Persian indigo",
    "d99058" -> "Persian orange",
    "f77fbe" -> "Persian pink",
    "701c1c" -> "Persian plum",
    "cc3333" -> "Persian red",
    "fe28a2" -> "Persian rose",
    "df00ff" -> "Phlox",
    "000f89" -> "Phthalo blue",
    "123524" -> "Phthalo green",
    "fddde6" -> "Piggy pink",
    "01796f" -> "Pine green",
    "ffc0cb" -> "Pink",
    "fc74fd" -> "Pink Flamingo",
    "f78fa7" -> "Pink Sherbet",
    "e7accf" -> "Pink pearl",
    "93c572" -> "Pistachio",
    "e5e4e2" -> "Platinum",
    "dda0dd" -> "Plum",
    "ff5a36" -> "Portland Orange",
    "b0e0e6" -> "Powder blue",
    "ff8f00" -> "Princeton orange",
    "003153" -> "Prussian blue",
    "df00ff" -> "Psychedelic purple",
    "cc8899" -> "Puce",
    "ff7518" -> "Pumpkin",
    "800080" -> "Purple",
    "69359c" -> "Purple Heart",
    "9678b6" -> "Purple mountain majesty",
    "fe4eda" -> "Purple pizzazz",
    "50404d" -> "Purple taupe",
    "5d8aa8" -> "Rackley",
    "ff355e" -> "Radical Red",
    "e30b5d" -> "Raspberry",
    "915f6d" -> "Raspberry glace",
    "e25098" -> "Raspberry pink",
    "b3446c" -> "Raspberry rose",
    "d68a59" -> "Raw Sienna",
    "ff33cc" -> "Razzle dazzle rose",
    "e3256b" -> "Razzmatazz",
    "ff0000" -> "Red",
    "ff5349" -> "Red Orange",
    "a52a2a" -> "Red brown",
    "c71585" -> "Red violet",
    "004040" -> "Rich black",
    "d70040" -> "Rich carmine",
    "0892d0" -> "Rich electric blue",
    "b666d2" -> "Rich lilac",
    "b03060" -> "Rich maroon",
    "414833" -> "Rifle green",
    "ff007f" -> "Rose",
    "f9429e" -> "Rose bonbon",
    "674846" -> "Rose ebony",
    "b76e79" -> "Rose gold",
    "e32636" -> "Rose madder",
    "ff66cc" -> "Rose pink",
    "aa98a9" -> "Rose quartz",
    "905d5d" -> "Rose taupe",
    "ab4e52" -> "Rose vale",
    "65000b" -> "Rosewood",
    "d40000" -> "Rosso corsa",
    "bc8f8f" -> "Rosy brown",
    "0038a8" -> "Royal azure",
    "4169e1" -> "Royal blue",
    "ca2c92" -> "Royal fuchsia",
    "7851a9" -> "Royal purple",
    "e0115f" -> "Ruby",
    "ff0028" -> "Ruddy",
    "bb6528" -> "Ruddy brown",
    "e18e96" -> "Ruddy pink",
    "a81c07" -> "Rufous",
    "80461b" -> "Russet",
    "b7410e" -> "Rust",
    "00563f" -> "Sacramento State green",
    "8b4513" -> "Saddle brown",
    "ff6700" -> "Safety orange",
    "f4c430" -> "Saffron",
    "23297a" -> "Saint Patrick Blue",
    "ff8c69" -> "Salmon",
    "ff91a4" -> "Salmon pink",
    "c2b280" -> "Sand",
    "967117" -> "Sand dune",
    "ecd540" -> "Sandstorm",
    "f4a460" -> "Sandy brown",
    "967117" -> "Sandy taupe",
    "507d2a" -> "Sap green",
    "0f52ba" -> "Sapphire",
    "cba135" -> "Satin sheen gold",
    "ff2400" -> "Scarlet",
    "ffd800" -> "School bus yellow",
    "76ff7a" -> "Screamin Green",
    "006994" -> "Sea blue",
    "2e8b57" -> "Sea green",
    "321414" -> "Seal brown",
    "fff5ee" -> "Seashell",
    "ffba00" -> "Selective yellow",
    "704214" -> "Sepia",
    "8a795d" -> "Shadow",
    "45cea2" -> "Shamrock",
    "009e60" -> "Shamrock green",
    "fc0fc0" -> "Shocking pink",
    "882d17" -> "Sienna",
    "c0c0c0" -> "Silver",
    "cb410b" -> "Sinopia",
    "007474" -> "Skobeloff",
    "87ceeb" -> "Sky blue",
    "cf71af" -> "Sky magenta",
    "6a5acd" -> "Slate blue",
    "708090" -> "Slate gray",
    "003399" -> "Smalt",
    "933d41" -> "Smokey topaz",
    "100c08" -> "Smoky black",
    "fffafa" -> "Snow",
    "0fc0fc" -> "Spiro Disco Ball",
    "a7fc00" -> "Spring bud",
    "00ff7f" -> "Spring green",
    "4682b4" -> "Steel blue",
    "fada5e" -> "Stil de grain yellow",
    "990000" -> "Stizza",
    "008080" -> "Stormcloud",
    "e4d96f" -> "Straw",
    "ffcc33" -> "Sunglow",
    "fad6a5" -> "Sunset",
    "fd5e53" -> "Sunset Orange",
    "d2b48c" -> "Tan",
    "f94d00" -> "Tangelo",
    "f28500" -> "Tangerine",
    "ffcc00" -> "Tangerine yellow",
    "483c32" -> "Taupe",
    "8b8589" -> "Taupe gray",
    "cd5700" -> "Tawny",
    "d0f0c0" -> "Tea green",
    "f4c2c2" -> "Tea rose",
    "008080" -> "Teal",
    "367588" -> "Teal blue",
    "006d5b" -> "Teal green",
    "e2725b" -> "Terra cotta",
    "d8bfd8" -> "Thistle",
    "de6fa1" -> "Thulian pink",
    "fc89ac" -> "Tickle Me Pink",
    "0abab5" -> "Tiffany Blue",
    "e08d3c" -> "Tiger eye",
    "dbd7d2" -> "Timberwolf",
    "eee600" -> "Titanium yellow",
    "ff6347" -> "Tomato",
    "746cc0" -> "Toolbox",
    "ffc87c" -> "Topaz",
    "fd0e35" -> "Tractor red",
    "808080" -> "Trolley Grey",
    "00755e" -> "Tropical rain forest",
    "0073cf" -> "True Blue",
    "417dc1" -> "Tufts Blue",
    "deaa88" -> "Tumbleweed",
    "b57281" -> "Turkish rose",
    "30d5c8" -> "Turquoise",
    "00ffef" -> "Turquoise blue",
    "a0d6b4" -> "Turquoise green",
    "66424d" -> "Tuscan red",
    "8a496b" -> "Twilight lavender",
    "66023c" -> "Tyrian purple",
    "0033aa" -> "UA blue",
    "d9004c" -> "UA red",
    "536895" -> "UCLA Blue",
    "ffb300" -> "UCLA Gold",
    "3cd070" -> "UFO Green",
    "014421" -> "UP Forest green",
    "7b1113" -> "UP Maroon",
    "990000" -> "USC Cardinal",
    "ffcc00" -> "USC Gold",
    "8878c3" -> "Ube",
    "ff6fff" -> "Ultra pink",
    "120a8f" -> "Ultramarine",
    "4166f5" -> "Ultramarine blue",
    "635147" -> "Umber",
    "5b92e5" -> "United Nations blue",
    "b78727" -> "University of California Gold",
    "ffff66" -> "Unmellow Yellow",
    "ae2029" -> "Upsdell red",
    "e1ad21" -> "Urobilin",
    "d3003f" -> "Utah Crimson",
    "f3e5ab" -> "Vanilla",
    "c5b358" -> "Vegas gold",
    "c80815" -> "Venetian red",
    "43b3ae" -> "Verdigris",
    "e34234" -> "Vermilion",
    "a020f0" -> "Veronica",
    "ee82ee" -> "Violet",
    "324ab2" -> "Violet Blue",
    "f75394" -> "Violet Red",
    "40826d" -> "Viridian",
    "922724" -> "Vivid auburn",
    "9f1d35" -> "Vivid burgundy",
    "da1d81" -> "Vivid cerise",
    "ffa089" -> "Vivid tangerine",
    "9f00ff" -> "Vivid violet",
    "004242" -> "Warm black",
    "00ffff" -> "Waterspout",
    "645452" -> "Wenge",
    "f5deb3" -> "Wheat",
    "ffffff" -> "White",
    "f5f5f5" -> "White smoke",
    "ff43a4" -> "Wild Strawberry",
    "fc6c85" -> "Wild Watermelon",
    "a2add0" -> "Wild blue yonder",
    "722f37" -> "Wine",
    "c9a0dc" -> "Wisteria",
    "738678" -> "Xanadu",
    "0f4d92" -> "Yale Blue",
    "ffff00" -> "Yellow",
    "ffae42" -> "Yellow Orange",
    "9acd32" -> "Yellow green",
    "0014a8" -> "Zaffre",
    "2c1608" -> "Zinnwaldite brown")
}

```

# Answer
> 6 votes
Well, since I had it laying around, here it is in Objective-C:

```
- (NSString*)colorNameFromColor:(NSColor*)chosenColor
{
    NSColor*    calibratedColor = [chosenColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace];

    CGFloat  hue;
    CGFloat  saturation;
    CGFloat  brightness;
    [calibratedColor getHue:&hue
                 saturation:&saturation
                 brightness:&brightness
                      alpha:nil];

    // I found that when the saturation was below 1% I couldn't tell
    // the color from gray
    if (saturation <= 0.01)
    {
        saturation = 0.0;
    }

    NSString*   colorName   = @"";

    // If saturation is 0.0, then this is a grayscale color
    if (saturation == 0.0)
    {
        if (brightness <= 0.2)
        {
            colorName = @"black";
        }
        else if (brightness > 0.95)
        {
            colorName = @"white";
        }
        else
        {
            colorName = @"gray";

            if (brightness < 0.33)
            {
                colorName = [@"dark " stringByAppendingString:colorName];
            }
            else if (brightness > 0.66)
            {
                colorName = [@"light " stringByAppendingString:colorName];
            }
        }
    }
    else
    {
        if ((hue <= 15.0 / 360.0) || (hue > 330.0 / 360.0))
        {
            colorName = @"red";
        }
        else if (hue < 45.0 / 360.0)
        {
            colorName = @"orange";
        }
        else if (hue < 70.0 / 360.0)
        {
            colorName = @"yellow";
        }
        else if (hue < 150.0 / 360.0)
        {
            colorName = @"green";
        }
        else if (hue < 190.0 / 360.0)
        {
            colorName = @"cyan";
        }
        else if (hue < 250.0 / 360.0)
        {
            colorName = @"blue";
        }
        else if (hue < 290.0 / 360.0)
        {
            colorName = @"purple";
        }
        else
        {
            colorName = @"magenta";
        }

        if (brightness < 0.5)
        {
            colorName = [@"dark " stringByAppendingString:colorName];
        }
        else if (brightness > 0.8)
        {
            colorName = [@"bright " stringByAppendingString:colorName];
        }
    }

    return colorName;
}

```

# Answer
> 5 votes
# Pharo Smalltalk

Put this in a Pharo Workspace and *print it*.

```
| color colorNames nearestColorName |
color := Color r: 255 g: 0 b: 0 range: 255.
colorNames := Color registeredColorNames copyWithout: #transparent.
nearestColorName := colorNames detectMin: [ :each | (Color named: each) diff: color].

```

The results are of mixed quality. All darker colors are named as *gray*, *dark gray* or *very dark gray*. Probably `Color`'s `diff:` method could be better.

For a very simple visualization *do*:

```
((Morph newBounds: (0@0 extent: 200@200 ) color: color) addMorph: nearestColorName asMorph) openInWorld.

```

# Answer
> 5 votes
SAS macro, based on the (rather quaint) SAS V8 colour names as documented here: https://v8doc.sas.com/sashtml/gref/zgscheme.htm#zrs-hues

Sample input:

```
%rgbname(100,100,50);

```

Sample output:

EDIT: Updated with much more compact version.

```
%macro rgbname(r,g,b);
data _null_;
    infile "C:\temp\colours.csv" dlm = ',' lrecl=32767 missover firstobs = 2 end = eof;
    format name description $32. rgb hls $8.;
    input name description rgb hls;
    R = input(substr(rgb,3,2),hex.);
    G = input(substr(rgb,5,2),hex.);
    B = input(substr(rgb,7,2),hex.);
    retain min_distance outdesc;
    distance = (r-&r)**2 + (g-&g)**2 + (b-&b)**2;
    min_distance = min(distance, min_distance);
    if distance = min_distance then outdesc = description;
    if eof then call symput("COLOUR_NAME", outdesc);
run;
dm log "postmessage ""You meant &COLOUR_NAME""" continue;
%mend rgbname;

```

XKCD version - a blatant ripoff of the top answer, but it's a nice little demo of the filename URL engine, and doesn't require manual preparation of a CSV:

```
%macro rgb_xkcd_name(r,g,b);
filename xkcd URL "http://bpaste.net/raw/402634/" debug;
data _null_;
    infile xkcd dlm = ',][' lrecl=32767 missover end = eof;
    format r g b 3. name $32.;
    input r g b name;
    retain min_distance outname;
    distance = (r-&r)**2 + (g-&g)**2 + (b-&b)**2;
    min_distance = min(distance, min_distance);
    if distance = min_distance then outname = name;
    if eof then do;
        call symput("COLOUR_NAME", outname);
        put _all_;
    end;
run;
dm log "postmessage ""XKCD thinks you meant &COLOUR_NAME""" continue;
%mend rgb_xkcd_name;

```

# Answer
> 5 votes
A C# Solution with Linq and KnownColors from .NET

```
string GetColorName(int r, int g, int b){
    return Enum.GetValues(typeof(KnownColor))
        .OfType<KnownColor>()
        .Select(x => Color.FromKnownColor(x))
        .Select(x => new {Col = x, Offset = Math.Abs(r - x.R) + Math.Abs(g - x.G) + Math.Abs(b - x.B)})
        .OrderBy(x => x.Offset)
        .Select(x => x.Col)
        .First().Name;
}

```

# Answer
> 4 votes
## Tcl

This references X11 colors from `rgb.txt`. On my Ubuntu it's in `/etc/X11/rgb.txt` though I know on some systems it's in `/usr/lib/X11/rgb.txt`. Google `rgb.txt` and download it if you don't run X11.

```
#! /usr/bin/env tclsh

set f [open /etc/X11/rgb.txt]
set raw [read $f]
close $f

set COLORS {}
foreach line [split $raw \n] {
    regexp {(\d+)\s+(\d+)\s+(\d+)\s+(.+)} $line -> r g b name
    if {[info exists name] && $name != ""} {
        lappend COLORS [format %02x%02x%02x $r $g $b] $name
    }
}

proc color_distance {a b} {
    set a [scan $a %2x%2x%2x]
    set b [scan $b %2x%2x%2x]
    set dist 0

    foreach x $a y $b {
        set dist [expr {$dist + (abs($x-$y)**2)}]
    }
    return $dist
}

proc identify {given_color} {
    global COLORS
    set d 0xffffff
    set n "not found"
    set c ""

    foreach {test_color name} $COLORS {
        set dist [color_distance $given_color $test_color]
        if {$dist < $d} {
            set d $dist
            set n $name
            set c $test_color
        }
    }

    return "$n ($c)"
}

puts [identify $argv]

```

Pass color code as command line argument.

# Answer
> 3 votes
# Python 2.6

## With UI:

### Obfuscated (8,397 bytes):

```
exec("import re;import base64");exec((lambda p,y:(lambda o,b,f:re.sub(o,b,f))(r"([0-9a-f]+)",lambda m:p(m,y),base64.b64decode("[encoded data, 5132 characters]")))(lambda a,b:b[int("0x"+a.group(1),16)],"0|1|2|3|4|5|6|7|colorCanvas1|colorDifs|a|instructionsLabel|colorCanvas|canvasText1|create_rectangle|green|greenEntry|return|canvasText|value|numbers|colorName|16|color|pady|padx|redEntry|blue|Application|not|valid|root|20|hex_to_rgb|range|Those|lightgoldenrodyellow|red|colorlist|colors|blueLabel|green_dif|mediumspringgreen|__init__|redLabel|rectFill|mediumaquamarine|blue_dif|Entry|mediumslateblue|mediumvioletred|mediumturquoise|convert|lightsteelblue|darkolivegreen|cornflowerblue|lightslategrey|mediumseagreen|red_dif|blanchedalmond|darkturquoise|darkslateblue|lightseagreen|darkslategray|darkgoldenrod|paleturquoise|lavenderblush|palevioletred|text|palegoldenrod|height|submit|lightskyblue|darkseagreen|greenLabel|antiquewhite|lemonchiffon|master|midnightblue|in|mediumorchid|sticky|def|green1|int|mediumpurple|self|are|Canvas|forestgreen|greenyellow|lightyellow|saddlebrown|darkmagenta|navajowhite|yellowgreen|deepskyblue|floralwhite|lightsalmon|springgreen|sandybrown|grid|lightgreen|blueviolet|darkviolet|lightcoral|Frame|mediumblue|whitesmoke|blue1|darksalmon|aquamarine|papayawhip|width|darkorchid|darkorange|ValueError|dodgerblue|powderblue|ghostwhite|chartreuse|darkgreen|darkkhaki|cadetblue|chocolate|mistyrose|Converter|indianred|000080|02x|lightcyan|steelblue|firebrick|turquoise|abs|slategray|get|palegreen|limegreen|00008b|256|rosybrown|slateblue|olivedrab|peachpuff|lawngreen|burlywood|royalblue|goldenrod|aliceblue|str|orangered|lightgray|mintcream|lightpink|geometry|seagreen|seashell|lavender|lv|fill|mainloop|darkcyan|deeppink|darkgray|moccasin|darkblue|honeydew|red1|loop|cornsilk|thistle|hotpink|Convert|dimgrey|oldlace|crimson|darkred|magenta|command|460x180|skyblue|Tkinter|708090|00ff7f|fdf5e6|e6e6fa|dda0dd|da70d6|ffefd5|ba55d3|b22222|maroon|fff0f5|fff8dc|f5fffa|d8bfd8|ff7f50|cd853f|gainsboro|87ceeb|adff2f|98fb98|f08080|f0e68c|0000cd|import|ff69b4|bisque|ff00ff|7fffd4|d3d3d3|f8f8ff|008080|6a5acd|778899|d87093|7cfc00|e9967a|9370d8|808000|afeeee|f5f5dc|20b2aa|for|c0c0c0|d2b48c|2e8b57|f5f5f5|8b4513|66cdaa|ffa500|fafad2|7b68ee|c71585|6b8e23|orange|faf0e6|4169e1|40e0d0|lightblue|ffffff|8a2be2|add8e6|7fff00|ffa07a|006400|fffff0|fff5ee|8b0000|6495ed|9400d3|ffd700|dcdcdc|00ced1|0000ff|dc143c|except|008000|f0fff0|808080|440|ffff00|f4a460|32cd32|f0ffff|87cefa|9acd32|4682b4|fffaf0|daa520|ffffe0|RGB|00ff00|fa8072|ff1493|008b8b|fffafa|b8860b|ff8c00|ffc0cb|191970|ffb6c1|00ffff|sienna|d2691e|cd5c5c|00fa9a|a52a2a|if|faebd7|800080|deb887|purple|4b0082|556b2f|bc8f8f|ffe4e1|8b008b|3cb371|ffe4b5|ee82ee|f0f8ff|a0522d|silver|violet|ffebcd|483d8b|1e90ff|ff6347|f5deb3|00bfff|eee8aa|000000|orchid|9932cc|2f4f4f|8fbc8f|ffe4c4|48d1cc|5f9ea0|salmon|800000|ff0000|fffacd|ffdab9|lstrip|ffdead|yellow|460|b0c4de|ff4500|Button|228b22|e0ffff|a9a9a9|b0e0e6|90ee90|bdb76b|696969|tomato|indigo|black|wheat|ivory|colorLabel|items|beige|Green|khaki|brown|olive|Enter|tuple|class|Color|linen|title|white|azure|coral|plum|peru|aqua|lime|from|Blue|Name|gold|snow|grey|teal|navy|pink|keys|try|i|len|app|Red|column|The|min|tan|to|Tk|row|hexValue|is|W|blueEntry|columnspan|Label".split("|")))

```

### Not Obfuscated (6,898 bytes):

```
from Tkinter import *
colorlist = {'#7cfc00': 'lawngreen', '#808080': 'grey', '#00008b': 'darkblue', '#ffe4b5': 'moccasin', '#fffff0': 'ivory', '#9400d3': 'darkviolet', '#b8860b': 'darkgoldenrod', '#fffaf0': 'floralwhite', '#8b008b': 'darkmagenta', '#fff5ee': 'seashell', '#ff8c00': 'darkorange', '#5f9ea0': 'cadetblue', '#2f4f4f': 'darkslategray', '#afeeee': 'paleturquoise', '#add8e6': 'lightblue', '#fffafa': 'snow', '#1e90ff': 'dodgerblue', '#000000': 'black', '#8fbc8f': 'darkseagreen', '#7fffd4': 'aquamarine', '#ffe4e1': 'mistyrose', '#800000': 'maroon', '#6495ed': 'cornflowerblue', '#4169e1': 'royalblue', '#40e0d0': 'turquoise', '#ffffff': 'white', '#00ced1': 'darkturquoise', '#8b0000': 'darkred', '#ee82ee': 'violet', '#adff2f': 'greenyellow', '#b0e0e6': 'powderblue', '#7b68ee': 'mediumslateblue', '#ff00ff': 'magenta', '#4682b4': 'steelblue', '#ff6347': 'tomato', '#00ff7f': 'springgreen', '#ffefd5': 'papayawhip', '#ffd700': 'gold', '#f5fffa': 'mintcream', '#dda0dd': 'plum', '#cd5c5c': 'indianred', '#ffa07a': 'lightsalmon', '#00fa9a': 'mediumspringgreen', '#f8f8ff': 'ghostwhite', '#008000': 'green', '#faebd7': 'antiquewhite', '#f0fff0': 'honeydew', '#c0c0c0': 'silver', '#228b22': 'forestgreen', '#7fff00': 'chartreuse', '#fafad2': 'lightgoldenrodyellow', '#fff8dc': 'cornsilk', '#f4a460': 'sandybrown', '#6b8e23': 'olivedrab', '#9932cc': 'darkorchid', '#fdf5e6': 'oldlace', '#3cb371': 'mediumseagreen', '#d8bfd8': 'thistle', '#808000': 'olive', '#a9a9a9': 'darkgray', '#f5f5dc': 'beige', '#f5deb3': 'wheat', '#ffa500': 'orange', '#00ff00': 'lime', '#90ee90': 'lightgreen', '#a0522d': 'sienna', '#8b4513': 'saddlebrown', '#00ffff': 'aqua', '#4b0082': 'indigo', '#66cdaa': 'mediumaquamarine', '#b22222': 'firebrick', '#d2b48c': 'tan', '#ffebcd': 'blanchedalmond', '#0000ff': 'blue', '#da70d6': 'orchid', '#fffacd': 'lemonchiffon', '#ff7f50': 'coral', '#f5f5f5': 'whitesmoke', '#ffc0cb': 'pink', '#f0e68c': 'khaki', '#ffffe0': 'lightyellow', '#f0ffff': 'azure', '#f0f8ff': 'aliceblue', '#daa520': 'goldenrod', '#c71585': 'mediumvioletred', '#b0c4de': 'lightsteelblue', '#fa8072': 'salmon', '#708090': 'slategray', '#ff1493': 'deeppink', '#6a5acd': 'slateblue', '#2e8b57': 'seagreen', '#e9967a': 'darksalmon', '#778899': 'lightslategrey', '#ba55d3': 'mediumorchid', '#ff4500': 'orangered', '#a52a2a': 'brown', '#696969': 'dimgrey', '#191970': 'midnightblue', '#dc143c': 'crimson', '#bdb76b': 'darkkhaki', '#ffff00': 'yellow', '#d87093': 'palevioletred', '#556b2f': 'darkolivegreen', '#9370d8': 'mediumpurple', '#eee8aa': 'palegoldenrod', '#cd853f': 'peru', '#faf0e6': 'linen', '#bc8f8f': 'rosybrown', '#d2691e': 'chocolate', '#008080': 'teal', '#98fb98': 'palegreen', '#ff69b4': 'hotpink', '#e0ffff': 'lightcyan', '#87cefa': 'lightskyblue', '#ffdead': 'navajowhite', '#483d8b': 'darkslateblue', '#32cd32': 'limegreen', '#e6e6fa': 'lavender', '#800080': 'purple', '#d3d3d3': 'lightgray', '#006400': 'darkgreen', '#0000cd': 'mediumblue', '#00bfff': 'deepskyblue', '#ffe4c4': 'bisque', '#48d1cc': 'mediumturquoise', '#008b8b': 'darkcyan', '#9acd32': 'yellowgreen', '#f08080': 'lightcoral', '#ff0000': 'red', '#deb887': 'burlywood', '#ffb6c1': 'lightpink', '#20b2aa': 'lightseagreen', '#87ceeb': 'skyblue', '#fff0f5': 'lavenderblush', '#8a2be2': 'blueviolet', '#000080': 'navy', '#dcdcdc': 'gainsboro', '#ffdab9': 'peachpuff'}

def hex_to_rgb(value):
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3))

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.loop()

    def loop(self):
        self.instructionsLabel = Label(self, text = "Enter in a RGB value.")
        self.instructionsLabel.grid(row = 1, column = 0, columnspan = 3)

        self.redLabel = Label(self, text = "Red")
        self.redLabel.grid(row = 2, column = 0, padx = 5, pady = 5)
        self.redEntry = Entry(self)
        self.redEntry.grid(row = 3, column = 0, padx = 5, pady = 5)

        self.greenLabel = Label(self, text = "Green")
        self.greenLabel.grid(row = 2, column = 1, padx = 5, pady = 5)
        self.greenEntry = Entry(self)
        self.greenEntry.grid(row = 3, column = 1, padx = 5, pady = 5)

        self.blueLabel = Label(self, text = "Blue")
        self.blueLabel.grid(row = 2, column = 2, padx = 5, pady = 5)
        self.blueEntry = Entry(self)
        self.blueEntry.grid(row = 3, column = 2, padx = 5, pady = 5)

        self.submit = Button(self, text = "Convert", command = self.convert)
        self.submit.grid(row = 4, column = 0, columnspan = 3)

        self.colorLabel = Label(self)
        self.colorLabel.grid(row = 5, column = 0, columnspan = 3)

        self.colorCanvas = Canvas(self, width = 460, height = 20)
        self.colorCanvas.grid(row = 6, column = 0, columnspan = 3)

        self.canvasText = Label(self)
        self.canvasText.grid(row = 6, column = 0, sticky = W)

        self.colorCanvas1 = Canvas(self, width = 460, height = 20)
        self.colorCanvas1.grid(row = 7, column = 0, columnspan = 3)

        self.canvasText1 = Label(self)
        self.canvasText1.grid(row = 7, column = 0, sticky = W)

    def convert(self):
        try:
            red = int(self.redEntry.get())
            green = int(self.greenEntry.get())
            blue = int(self.blueEntry.get())
        except ValueError:
            self.colorLabel["text"] = "Those are not valid numbers."
            return

        if red not in range(256):
            self.colorLabel["text"] = "Those are not valid numbers."
            return
        if green not in range(256):
            self.colorLabel["text"] = "Those are not valid numbers."
            return
        if blue not in range(256):
            self.colorLabel["text"] = "Those are not valid numbers."
            return

        colorDifs = {}
        colors = {}
        for hexValue, colorName in colorlist.items():
            colors[colorName] = hexValue
            red1, green1, blue1 = hex_to_rgb(hexValue)
            red_dif = abs(red1 - red)
            green_dif = abs(green1 - green)
            blue_dif = abs(blue1 - blue)
            colorDifs[red_dif + green_dif + blue_dif] = colorName
        color = colorDifs[min(colorDifs.keys())];

        hexValue = colors[color]

        rectFill = '#%02x%02x%02x' % (red, green, blue)

        self.colorLabel["text"] = "The color is " +  color
        self.canvasText["text"] = "(" + str(red) + ", " + str(green) + ", " + str(blue) + ")"
        self.canvasText1["text"] = color
        self.colorCanvas.create_rectangle(20, 0, 440, 20, fill = rectFill)
        self.colorCanvas1.create_rectangle(20, 0, 440, 20, fill = hexValue)

root = Tk()
root.title("RGB to Color Name Converter")
root.geometry("460x180")
app = Application(root)

root.mainloop()

```

### Without UI:

### Obfuscated (6,543 bytes):

```
exec("import re;import base64");exec((lambda p,y:(lambda o,b,f:re.sub(o,b,f))(r"([0-9a-f]+)",lambda m:p(m,y),base64.b64decode("MTMgPSB7JyMxMGYnOiAnNTcnLCAnIzExOCc6ICcxMzgnLCAnIzhiJzogJzc5JywgJyNmYyc6ICc3NScsICcjZDgnOiAnMTI2JywgJyNjNic6ICc1NScsICcjYTMnOiAnMjknLCAnIzkwJzogJzNkJywgJyNmMyc6ICc0MScsICcjZGEnOiAnNzcnLCAnIzEwMic6ICc0NycsICcjZTQnOiAnNWQnLCAnI2IxJzogJzJjJywgJyMxMTUnOiAnMmEnLCAnI2NjJzogJzcwJywgJyM5ZCc6ICcxM2UnLCAnIzhjJzogJzQ5JywgJyMxNGMnOiAnMTI5JywgJyNiMic6ICczNicsICcjZmInOiAnNDgnLCAnI2YwJzogJzY1JywgJyNkYyc6ICdhNScsICcjZTInOiAnMjEnLCAnI2JiJzogJzViJywgJyMxMjQnOiAnNjcnLCAnI2M3JzogJzEyYScsICcjZjYnOiAnMmUnLCAnI2RlJzogJzgxJywgJyMxMDEnOiAnMTFjJywgJyNkNSc6ICczYicsICcjMTA5JzogJzRiJywgJyNhOSc6ICcxZCcsICcjZjUnOiAnODQnLCAnIzkxJzogJzU4JywgJyM4ZCc6ICcxMWEnLCAnIzk1JzogJzQzJywgJyM5YSc6ICc1MCcsICcjZDMnOiAnMTNiJywgJyNiNic6ICc1ZScsICcjOTMnOiAnMTNhJywgJyNiZic6ICc2YycsICcjZjknOiAnM2YnLCAnI2MzJzogJzE0ZScsICcjMTAzJzogJzUyJywgJyMxMTAnOiAnMTRmJywgJyNjZic6ICczNCcsICcjMTE2JzogJzc2JywgJyM4Zic6ICcxMTknLCAnI2ZkJzogJzM5JywgJyNjZSc6ICc1NCcsICcjYTgnOiAnMTInLCAnI2FjJzogJzdlJywgJyMxMWQnOiAnNDUnLCAnI2IzJzogJzU5JywgJyNhYic6ICc1MycsICcjYjUnOiAnODYnLCAnI2Y4JzogJzIzJywgJyNiZSc6ICc4MicsICcjMTEzJzogJzEyZScsICcjZWInOiAnN2YnLCAnIzEyMic6ICcxMmInLCAnI2RkJzogJzEzMycsICcjOWUnOiAnYjQnLCAnI2Y3JzogJzEzNycsICcjMTBlJzogJzQ2JywgJyNkZic6ICdiYycsICcjY2InOiAnNDAnLCAnI2I4JzogJzEzNicsICcjMTA2JzogJzExZScsICcjOWMnOiAnMTgnLCAnIzlmJzogJzY0JywgJyM5Mic6ICcxNDgnLCAnIzExZic6ICcyNicsICcjZmYnOiAnNScsICcjOTYnOiAnYTInLCAnI2UwJzogJzM4JywgJyNjMCc6ICcxMzUnLCAnIzk4JzogJzUxJywgJyNhZSc6ICcxNDAnLCAnI2U3JzogJzEyNScsICcjOTcnOiAnM2MnLCAnIzEyMyc6ICcxMzEnLCAnI2M4JzogJzY4JywgJyM5OSc6ICc2NicsICcjYWQnOiAnMWMnLCAnI2Y0JzogJzI1JywgJyNiYSc6ICdkYicsICcjYzEnOiAnNmInLCAnI2UxJzogJzdjJywgJyMxMGEnOiAnNjEnLCAnI2Q5JzogJzdhJywgJyNhMCc6ICc0YScsICcjZWMnOiAnMjQnLCAnI2M5JzogJzM3JywgJyM5NCc6ICc2ZCcsICcjYzQnOiAnMTJkJywgJyMxMTcnOiAnODUnLCAnI2IwJzogJzMwJywgJyMxMDQnOiAnODgnLCAnI2ZlJzogJzVjJywgJyMxMWInOiAnZWYnLCAnIzEwZCc6ICcyNycsICcjZTgnOiAnMjInLCAnIzExMSc6ICczMScsICcjOGUnOiAnMmYnLCAnI2NhJzogJzEzYycsICcjYjknOiAnMTI3JywgJyNlYSc6ICc2MCcsICcjYmQnOiAnNjMnLCAnIzEwOCc6ICcxMzknLCAnI2Q2JzogJzcyJywgJyMxMDUnOiAnODMnLCAnI2FmJzogJzczJywgJyMxMGMnOiAnMzUnLCAnI2VlJzogJzNhJywgJyM4OSc6ICcyZCcsICcjMTIwJzogJzVhJywgJyNhYSc6ICc3OCcsICcjMTA3JzogJ2Q3JywgJyMxMDAnOiAnNmYnLCAnI2VkJzogJzU2JywgJyNjZCc6ICc0ZScsICcjMTEyJzogJzQyJywgJyNjNSc6ICdmMicsICcjYzInOiAnMWYnLCAnIzliJzogJzhhJywgJyNkMCc6ICczZScsICcjYTQnOiAnNDQnLCAnIzEwYic6ICdhJywgJyNkNCc6ICc2YScsICcjYjcnOiAnNzQnLCAnIzExNCc6ICcyYicsICcjZDEnOiAnODcnLCAnI2E3JzogJzI4JywgJyNmYSc6ICc0YycsICcjODAnOiAnMTNmJywgJyNlNic6ICc1ZicsICcjZTMnOiAnNzEnfQoxMjEgMTAoNyk6Cgk3ID0gNy5lOSgnIycpCgk3YiA9IDE0OSg3KQoJMzIgMTM0KGUoN1sxNDY6MTQ2KzdiLzNdLCAxNikgZjEgMTQ2IDRkIGYoMTRjLCA3YiwgN2IvMykpCgoxMjEgMWIoNik6CglkID0ge307CglmMSAxYSwgNCA0ZCAxMy4xMzIoKToKCQlhLCAxNGYsIDUgPSAxMCgxYSk7CgkJMjAgPSA2OShhIC0gNlsxNGNdKTsKCQkxNSA9IDY5KDE0ZiAtIDZbMV0pCgkJMTcgPSA2OSg1IC0gNlsyXSkKCQlkWzIwICsgMTUgKyAxN10gPSA0CgkzMiBkWzE0NShkLjEzZCgpKV07CgoxMSAxOToKCgljICJhNiAxMjggMTQ0IDE0MiA3LiI7CglhMSgiLS0xMmYgMTJjIDE0ZCA3ZC0tXDRmPiAiKTsKCglhLCAxNGYsIDUgPSAiIiwgIiIsICIiOwoJYSA9IGExKCIxNDdcNGY+ICIpOwoJMTEgMTk6CgkJYjoKCQkJZTUgZShhKSA2MiA0ZCBmKDZlKToKCQkJCWEgPSBhMSgiLS0xNGItLVwxNTAgYiA4XDRmPiAiKTsKCQkJMzM6CgkJCQkxZTsKCQkxNCA5OgoJCQlhID0gYTEoIi0tMTRiLS1cMTUwIGIgOFw0Zj4gIik7CgoJMTRmID0gYTEoIjEzMFw0Zj4gIik7CgkxMSAxOToKCQliOgoJCQllNSBlKDE0ZikgNjIgNGQgZig2ZSk6CgkJCQkxNGYgPSBhMSgiLS0xNGItLVwxNTAgYiA4XDRmPiAiKTsKCQkJMzM6CgkJCQkxZTsKCQkxNCA5OgoJCQkxNGYgPSBhMSgiLS0xNGItLVwxNTAgYiA4XDRmPiAiKTsKCgk1ID0gYTEoIjE0MVw0Zj4gIik7CgkxMSAxOToKCQliOgoJCQllNSBlKDUpIDYyIDRkIGYoNmUpOgoJCQkJNSA9IGExKCItLTE0Yi0tXDE1MCBiIDhcNGY+ICIpOwoJCQkzMzoKCQkJCTFlOwoJCTE0IDk6CgkJCTUgPSBhMSgiLS0xNGItLVwxNTAgYiA4XDRmPiAiKTsKCglkMiA9IChlKGEpLCBlKDE0ZiksIGUoNSkpOwoJNCA9IDFiKGQyKTsKCgljICIxNDMgMWIgMTRhIiwgNDsKCWMKCWMKCWM=")))(lambda a,b:b[int("0x"+a.group(1),16)],"000000|1|2|3|colorName|blue|rgbValue|value|again|ValueError|red|try|print|colors|int|range|hex_to_rgb|while|lightgoldenrodyellow|colorlist|except|green_dif|16|blue_dif|mediumaquamarine|True|hexValue|color|mediumvioletred|mediumslateblue|break|mediumturquoise|red_dif|cornflowerblue|darkolivegreen|mediumseagreen|lightslategrey|lightsteelblue|blanchedalmond|palevioletred|lavenderblush|darkgoldenrod|paleturquoise|lightseagreen|darkslategray|darkslateblue|darkturquoise|palegoldenrod|midnightblue|mediumpurple|return|else|antiquewhite|lightskyblue|darkseagreen|mediumorchid|lemonchiffon|forestgreen|navajowhite|greenyellow|lightyellow|floralwhite|yellowgreen|lightsalmon|saddlebrown|darkmagenta|deepskyblue|springgreen|lightcoral|sandybrown|lightgreen|darkorange|aquamarine|dodgerblue|darksalmon|powderblue|blueviolet|in|mediumblue|n|papayawhip|whitesmoke|ghostwhite|darkorchid|chartreuse|darkviolet|darkgreen|lawngreen|steelblue|olivedrab|limegreen|royalblue|darkkhaki|cadetblue|mintcream|gainsboro|rosybrown|slateblue|not|chocolate|firebrick|mistyrose|goldenrod|turquoise|aliceblue|abs|burlywood|slategray|indianred|orangered|256|lightgray|lightblue|peachpuff|palegreen|lightcyan|lightpink|moccasin|honeydew|seashell|lavender|darkblue|seagreen|lv|deeppink|continue|cornsilk|darkgray|000080|darkred|thistle|hotpink|magenta|dimgrey|oldlace|skyblue|crimson|483d8b|darkcyan|00008b|1e90ff|ff6347|eee8aa|c0c0c0|fffaf0|4682b4|d2b48c|dda0dd|ff4500|00ff7f|da70d6|ffffe0|f5f5f5|daa520|ffefd5|008b8b|66cdaa|fffafa|ffa500|b22222|e9967a|raw_input|orchid|b8860b|f08080|maroon|Please|fff0f5|fafad2|7b68ee|e6e6fa|9932cc|fff8dc|c71585|ffc0cb|e0ffff|191970|2f4f4f|8fbc8f|6b8e23|orange|fdf5e6|f5fffa|ffb6c1|00ffff|faf0e6|fa8072|4169e1|sienna|d2691e|d8bfd8|cd5c5c|ff7f50|708090|48d1cc|00fa9a|a52a2a|ffe4c4|9400d3|ffffff|f0f8ff|ba55d3|cd853f|8b4513|add8e6|0000cd|7fff00|faebd7|9acd32|87ceeb|rgb|ffd700|deb887|adff2f|98fb98|purple|fffff0|2e8b57|fff5ee|salmon|800000|f5deb3|8b0000|a0522d|fffacd|ff1493|6495ed|ffdab9|5f9ea0|if|dcdcdc|f0e68c|556b2f|lstrip|bc8f8f|a9a9a9|778899|006400|ffdead|yellow|ffe4e1|for|bisque|8b008b|b0c4de|ff00ff|00ced1|00ff00|3cb371|ffa07a|8a2be2|7fffd4|ffe4b5|228b22|bdb76b|0000ff|d3d3d3|ee82ee|ff8c00|f8f8ff|dc143c|ff69b4|4b0082|800080|008080|b0e0e6|6a5acd|ff0000|87cefa|d87093|90ee90|7cfc00|008000|9370d8|00bfff|808000|20b2aa|afeeee|f0fff0|696969|808080|silver|tomato|ffff00|violet|f4a460|indigo|ffebcd|32cd32|def|f5f5dc|f0ffff|40e0d0|khaki|ivory|linen|input|black|white|beige|ENTER|brown|olive|Press|GREEN|azure|items|wheat|tuple|coral|aqua|lime|grey|teal|plum|gold|peru|keys|snow|navy|pink|BLUE|RGB|The|the|min|i|RED|tan|len|is|INVALID|0|to|mediumspringgreen|green|nPlease".split("|")))

```

### Not Obfuscated (5,050 bytes):

```
colorlist = {'#7cfc00': 'lawngreen', '#808080': 'grey', '#00008b': 'darkblue', '#ffe4b5': 'moccasin', '#fffff0': 'ivory', '#9400d3': 'darkviolet', '#b8860b': 'darkgoldenrod', '#fffaf0': 'floralwhite', '#8b008b': 'darkmagenta', '#fff5ee': 'seashell', '#ff8c00': 'darkorange', '#5f9ea0': 'cadetblue', '#2f4f4f': 'darkslategray', '#afeeee': 'paleturquoise', '#add8e6': 'lightblue', '#fffafa': 'snow', '#1e90ff': 'dodgerblue', '#000000': 'black', '#8fbc8f': 'darkseagreen', '#7fffd4': 'aquamarine', '#ffe4e1': 'mistyrose', '#800000': 'maroon', '#6495ed': 'cornflowerblue', '#4169e1': 'royalblue', '#40e0d0': 'turquoise', '#ffffff': 'white', '#00ced1': 'darkturquoise', '#8b0000': 'darkred', '#ee82ee': 'violet', '#adff2f': 'greenyellow', '#b0e0e6': 'powderblue', '#7b68ee': 'mediumslateblue', '#ff00ff': 'magenta', '#4682b4': 'steelblue', '#ff6347': 'tomato', '#00ff7f': 'springgreen', '#ffefd5': 'papayawhip', '#ffd700': 'gold', '#f5fffa': 'mintcream', '#dda0dd': 'plum', '#cd5c5c': 'indianred', '#ffa07a': 'lightsalmon', '#00fa9a': 'mediumspringgreen', '#f8f8ff': 'ghostwhite', '#008000': 'green', '#faebd7': 'antiquewhite', '#f0fff0': 'honeydew', '#c0c0c0': 'silver', '#228b22': 'forestgreen', '#7fff00': 'chartreuse', '#fafad2': 'lightgoldenrodyellow', '#fff8dc': 'cornsilk', '#f4a460': 'sandybrown', '#6b8e23': 'olivedrab', '#9932cc': 'darkorchid', '#fdf5e6': 'oldlace', '#3cb371': 'mediumseagreen', '#d8bfd8': 'thistle', '#808000': 'olive', '#a9a9a9': 'darkgray', '#f5f5dc': 'beige', '#f5deb3': 'wheat', '#ffa500': 'orange', '#00ff00': 'lime', '#90ee90': 'lightgreen', '#a0522d': 'sienna', '#8b4513': 'saddlebrown', '#00ffff': 'aqua', '#4b0082': 'indigo', '#66cdaa': 'mediumaquamarine', '#b22222': 'firebrick', '#d2b48c': 'tan', '#ffebcd': 'blanchedalmond', '#0000ff': 'blue', '#da70d6': 'orchid', '#fffacd': 'lemonchiffon', '#ff7f50': 'coral', '#f5f5f5': 'whitesmoke', '#ffc0cb': 'pink', '#f0e68c': 'khaki', '#ffffe0': 'lightyellow', '#f0ffff': 'azure', '#f0f8ff': 'aliceblue', '#daa520': 'goldenrod', '#c71585': 'mediumvioletred', '#b0c4de': 'lightsteelblue', '#fa8072': 'salmon', '#708090': 'slategray', '#ff1493': 'deeppink', '#6a5acd': 'slateblue', '#2e8b57': 'seagreen', '#e9967a': 'darksalmon', '#778899': 'lightslategrey', '#ba55d3': 'mediumorchid', '#ff4500': 'orangered', '#a52a2a': 'brown', '#696969': 'dimgrey', '#191970': 'midnightblue', '#dc143c': 'crimson', '#bdb76b': 'darkkhaki', '#ffff00': 'yellow', '#d87093': 'palevioletred', '#556b2f': 'darkolivegreen', '#9370d8': 'mediumpurple', '#eee8aa': 'palegoldenrod', '#cd853f': 'peru', '#faf0e6': 'linen', '#bc8f8f': 'rosybrown', '#d2691e': 'chocolate', '#008080': 'teal', '#98fb98': 'palegreen', '#ff69b4': 'hotpink', '#e0ffff': 'lightcyan', '#87cefa': 'lightskyblue', '#ffdead': 'navajowhite', '#483d8b': 'darkslateblue', '#32cd32': 'limegreen', '#e6e6fa': 'lavender', '#800080': 'purple', '#d3d3d3': 'lightgray', '#006400': 'darkgreen', '#0000cd': 'mediumblue', '#00bfff': 'deepskyblue', '#ffe4c4': 'bisque', '#48d1cc': 'mediumturquoise', '#008b8b': 'darkcyan', '#9acd32': 'yellowgreen', '#f08080': 'lightcoral', '#ff0000': 'red', '#deb887': 'burlywood', '#ffb6c1': 'lightpink', '#20b2aa': 'lightseagreen', '#87ceeb': 'skyblue', '#fff0f5': 'lavenderblush', '#8a2be2': 'blueviolet', '#000080': 'navy', '#dcdcdc': 'gainsboro', '#ffdab9': 'peachpuff'}
def hex_to_rgb(value):
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3))

def color(rgbValue):
    colors = {};
    for hexValue, colorName in colorlist.items():
        red, green, blue = hex_to_rgb(hexValue);
        red_dif = abs(red - rgbValue[0]);
        green_dif = abs(green - rgbValue[1])
        blue_dif = abs(blue - rgbValue[2])
        colors[red_dif + green_dif + blue_dif] = colorName
    return colors[min(colors.keys())];

while True:

    print "Please input the RGB value.";
    raw_input("--Press ENTER to continue--\n> ");

    red, green, blue = "", "", "";
    red = raw_input("RED\n> ");
    while True:
        try:
            if int(red) not in range(256):
                red = raw_input("--INVALID--\nPlease try again\n> ");
            else:
                break;
        except ValueError:
            red = raw_input("--INVALID--\nPlease try again\n> ");

    green = raw_input("GREEN\n> ");
    while True:
        try:
            if int(green) not in range(256):
                green = raw_input("--INVALID--\nPlease try again\n> ");
            else:
                break;
        except ValueError:
            green = raw_input("--INVALID--\nPlease try again\n> ");

    blue = raw_input("BLUE\n> ");
    while True:
        try:
            if int(blue) not in range(256):
                blue = raw_input("--INVALID--\nPlease try again\n> ");
            else:
                break;
        except ValueError:
            blue = raw_input("--INVALID--\nPlease try again\n> ");

    rgb = (int(red), int(green), int(blue));
    colorName = color(rgb);

    print "The color is", colorName;
    print
    print
    print

```

# Answer
> 3 votes
# Javascript

https://jsfiddle.net/SuperJedi224/goxyhm7a/

Some sample results \[as of July 31\] (colors listed are, in order, the one it determines as the closest and the one it determines as the second closest; except where only one is given, in which case it was determined to be an exact match):

Bright Navy Blue / Steel Blue

Bronze / Tan Yellow Orange

Topaz / Pear

Slime Green / Olive Green

Viridian / Emerald

# Answer
> 0 votes
VB.net

```
Function ColorName(r AS Integer, g As Integer, b As Integer)As String
  Dim nc = Color.FromArgb(255, r, g, b)
  For Each ob In [Enum].GetValues(GetType(System.Drawing.KnownColor))
    Dim c = Color.FromKnownColor(CType(ob, System.Drawing.KnownColor))
    If (c.R = nc.R) AndAlso (c.B = nc.B) AndAlso (c.G = nc.G) Then Return c.Name
  Next
  Return nc.Name
End Function

```

---
Tags: popularity-contest
---


title: Knödel numbers - Find Kn

text:
# Question
Title: Knödel numbers - Find Kn
The Knödel numbers are a set of sequences. Specifically, the Knödel numbers for a positive integer \\$n\\$ are the set of composite numbers \\$m\\$, such that all \\$i \< m\\$, coprime to \\$m\\$, satisfy \\$i^{(m-n)} \equiv 1 \mod m\\$. The set of Knödel numbers for a specific \\$n\\$ is denoted \\$K\_n\\$. (Wikipedia).

For example, \\$K\_1\\$ are the Carmichael numbers, and OEIS A002997. They go like: \\$\\{561, 1105, 1729, 2465, 2821, 6601, ... \\}\\$. \\$K\_2\\$ is OEIS A050990 and goes like, \\$\\{4, 6, 8, 10, 12, 14, 22, 24, 26, ... \\}\\$.

## Your task

Your task is to write a program/function/etc. that takes two numbers, \\$n\\$ and \\$p\\$. It should return the first \\$p\\$ numbers of the Knödel Sequence, \\$K\_n\\$.

This is , so shortest code in bytes wins!

## Examples

```
1, 6   ->   [561, 1105, 1729, 2465, 2821, 6601]
2, 3   ->   [4, 6, 8]
4, 9   ->   [6, 8, 12, 16, 20, 24, 28, 40, 44]
3, 1   ->   [9]
3, 0   ->   []
21, 21 ->   [45, 57, 63, 85, 105, 117, 147, 231, 273, 357, 399, 441, 483, 585, 609, 651, 741, 777, 861, 903, 987]

```

# Answer
# Pyth, ~~29~~ 28 bytes

```
.f&tPZ!f&q1iTZt%^T-ZQZSZvzhQ

```

*1 byte saved thanks to Jakube and orlp.*

Demonstration.

Input in the form

```
p
n

```

A fairly straightforward calculation. Relative primeness is checked via Pyth's gcd function. This code showcases `.f`, Pyth's "first n satisfying" function.

I have incorporated the implicit condition that `m > n` by starting the search for `m` values at `n + 1`.
> 7 votes

# Answer
# Haskell, 89 bytes

Very straightforward implementation. Defines a binary operator `n!p`.

```
n!p=take p[m|m<-[n+1..],any((<1).mod m)[2..m-1],and[i^(m-n)`mod`m<2|i<-[1..m],gcd i m<2]]

```

Example:

```
Prelude> 4!9
[6,8,12,16,20,24,28,40,44]

```
> 5 votes

# Answer
# Haskell, 90

```
a#b=gcd a b>1
n!p=take p[m|m<-[n+1..],any(m#)[2..m-1],all(\i->m#i||mod(i^(m-n))m<2)[1..m]]

```

much the same as @Marius 's answer, though developed independently.
> 2 votes

---
Tags: code-golf, math, sequence, number-theory
---


title: Write a D*mn Unambiguous Censor

text:
# Question
Title: Write a D*mn Unambiguous Censor
Censors are a common tool used on the interwebs. But they often censor too much of the word, and thus make the cursing ambiguous to the reader. And sometimes they don't censor enough, so the words still remain offending. Your task is to fix that.

## Your task

Write a program/function/whatever that takes two lists and a string. The first list will be the dictionary of all words in your language like: `["hello", "goodbye", "belgium", "offensive", "jumping", "hypercool"]`. The next will be subset of the first list containing all of the *offensive* words in the language: `["belgium", "offensive"]`. The words in these lists are guaranteed to contain only lowercase letters of the alphabet.

The string is the phrase you will have to censor. It will be made of words from the dictionary, separated by spaces: `"Goodbye offensive belgium"`

The return value will be that phrase censored. However, you have to censor in a certain way. Specifically, for each word in the offensive list, you have to *censor as many letters as possible while remaining completely unambiguous in the main dictionary.* So here it would be: `Goodbye o******** b******`.

## Clarifications

* Your code has to interpret the words case-insensitively, but return with the initial capitalization.
* If there are multiple optimal answers, pick any of them.
* If unambiguous censoring is impossible, censor a single letter that has the least number of other possible interpretations (If multiple are possible, again, its your choice).

## Test Cases

```
["hello", "goodbye", "belgium", "offensive", "jumping", "hypercool"] ["belgium", "offensive"] "Goodbye offensive belgium" -> "Goodbye o******** b******"
["word"] ["word"] "word" -> "****"
["hot", "hat", "bat", "had"] ["hat"] "hat" -> "*at" or "h*t" or "ha*"
https://gist.github.com/deekayen/4148741 ["quart"] "I am a quart" -> "I am a q**r*"

```

This is so shortest d\*mn code in bytes wins!

P.S. Anyone caught the reference with belgium? ;P

# Answer
> 3 votes
# JavaScript ES7, 194 bytes

```
(d,c,s,g=(a,b)=>[...b].reduce((z,l,i)=>z+(a[i]==l?1:0),0))=>[for(s of s.split` `)~d.indexOf(s)?[...c[(x=[for(i of c)g(i,s)]).indexOf(Math.max(...x))]].map((l,i)=>l!=s[i]?`*`:l).join``:s].join` `

```

A very large function. I'm guessing a few bytes can be golfed off but not much unless I completely change the way it works.

---
Tags: code-golf, natural-language
---


title: Sinusoidal text

text:
# Question
Title: Sinusoidal text
**Goal:** Write a program or function which prints an input string in a sinusoidal shape.

### The ASCII sinusoid

Here is one period of the sinusoid:

```
         .......
      ...       ...
    ..             ..
   .                 .
  .                   .
 .                     .
.                       .                       .
                         .                     .
                          .                   .
                           .                 .
                            ..             ..
                              ...       ...
                                 .......

```

Note that there is exactly one dot on each column.

* Each character in the input string will replace a dot in the shape above, from left to right.
* Spaces in the input have to be outputted like normal characters, in place of a dot.
* The starting character corresponds to the leftmost dot in the figure above.
* This is only one period, inputs can be longer than the number of dots above.

### Input

* Inputs are ASCII strings that contain only characters between ASCII decimal 32 (space) and ASCII decimal 126 (Tilde ~).
* Inputs will always be one line only (no linebreaks).
* Inputs can be taken via STDIN, function parameters, command line arguments, or anything similar.

### Output

* Output must be printed exactly like they are in the test cases given.
* Trailing spaces on lines are allowed as long as the length of the line with those trailing spaces does not exceed the length of the longest line (the one with the last character on it).
* No leading/trailing line allowed.

### Test cases

* Input: `.................................................`

Output:

```
         .......
      ...       ...
    ..             ..
   .                 .
  .                   .
 .                     .
.                       .                       .
                         .                     .
                          .                   .
                           .                 .
                            ..             ..
                              ...       ...
                                 .......

```
* Input: `Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.`

Output:

```
         ng Puzz                                         ion and                                         siasts                                          stratio
      mmi       les                                   est        an                                   thu       and                                   egi       n r
    ra              &                               qu             sw                               en              c                                r             eq
   g                                                                 e                                               o                             o                 u
  o                   C                           a                   r                           e                   d                           n                   i
 r                     o                                                                         l                     e                                               r
P                       d                       s                       s                       z                                               ,                       e
                         e                     i                         i                     z                         g                     e                         d
                                                                          t                   u                           o                   e                           .
                           G                 e                             e                 p                             l                 r
                            ol             ng                                f             g                                fe              f
                              f S       cha                                   or        min                                   rs.       00%
                                 tack Ex                                         program                                          It's 1

```
* Input: `Short text.`

Output:

```
         t.
      tex
    t
   r
  o
 h
S

```
* Input: `The quick brown fox jumps over the lazy dog`

Output:

```
          brown
      ick       fox
    qu              j
                     u
  e                   m
 h                     p
T                       s

                          o
                           v
                            er
                               th       dog
                                 e lazy

```

### Scoring

This is , so the shortest program or function in bytes wins.

# Answer
> 7 votes
# Pyth, 59 bytes (57 characters)

```
Xjb.sC.>V+R*12\ Xz\ C9*+-L12K+JsM._+6jC\཈2tP_JKlz]*dlzC9d

```

Demonstration.

A binary lookup table is encoded inside , which has value 3912. This is converted to binary, giving `[1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0]`. This is treated as the differences between consecutive heights. By prepending a 6, forming all prefixes and mapping each to its sum, the first quarter of the wave is generated.

`sM._+6jC\཈2` evaluates to `[6, 7, 8, 9, 10, 10, 11, 11, 11, 12, 12, 12, 12]` as described above. Then, the code concatenates on the reverse of this string to form the first half of the wave, and then subtracts it from 12 to give the entire wave.

Then, we form lines of each input character followed by 12 spaces. This line is rotated to the right by the wave height parameter corresponding to that location, and then the lines are transposed and joined on newlines.

Then, we strip off leading and trailing blank lines. However, we can't strip off leading or trailing blank lines that have spaces from the input. This is implemented by replacing spaces in the input with tabs (`C9`), which can't be in the input, stripping blank lines, and turning the tabs back into spaces.

# Answer
> 13 votes
## Python 2, 156 bytes

```
l=map(int,"654322111%08d1122345"%1);l+=[12-c for c in l]
def f(t):
 h=len(t);o=bytearray(' '*h+'\n')*13;i=0
 for c in t:o[i-~h*l[i%48]]=c;i+=1
 print o[:-1]

```

## Explanation

* The whole code simply makes a block of spaces (`o`) and replaces the right spaces with the letters of the input `t`.
* The variable `l` stores a list of offsets from the top. So that the `n`th character of `t` should be on line `l[n]`.
* The bytearray `o` serves as a mutable string, since strings are immutable in python.
* `-~h` is the same as `h+1` but saves space because I don't need parentheses.

# Answer
> 7 votes
## Java, 219 209 199 bytes

```
void p(char[]s){int r=6,c;String t="";for(;r>-7;r--,t+='\n')for(c=0;c<s.length;c++)t+=(s(c%48)==r?s[c]:' ');System.out.println(t);}int s(int a){return a<4?a:a<6?4:a<9?5:a<15?6:a<24?s(24-a):-s(a-24);}

```

I'm still a newbie here, and hope that it is compliant to the rules to introduce a sub-function (when the bytes of this function are counted, of course). If not, I'll try to convert the `sin` function into some clever array lookup...

```
public class SinusText
{
    public static void main(String[] args)
    {
        SinusText s = new SinusText();
        s.p(".................................................".toCharArray());
        s.p("Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.".toCharArray());
        s.p("Short text.".toCharArray());
        s.p("The quick brown fox jumps over the lazy dog".toCharArray());
    }
    void p(char[]s){int r=6,c;String t="";for(;r>-7;r--,t+='\n')for(c=0;c<s.length;c++)t+=(s(c%48)==r?s[c]:' ');System.out.println(t);}int s(int a){return a<4?a:a<6?4:a<9?5:a<15?6:a<24?s(24-a):-s(a-24);}
}

```

# Answer
> 4 votes
# Perl 5 \+ `-lF -Mbigint -M5.10.0`, 97 bytes

Coming back to this after a while it's nice to see how much my approach to this kind of thing has improved, -123 bytes!

```
eval's!.!(@l=654322111000000011122345=~/./g,map{12-$_}@l)[pos()%48]-$-?$":$F[pos]!ge;$-+=say;'x13

```

Try it online!

## Explanation

Input is implicitly placed in `$_` (due to `-n`, and `-a`, being implicitly set by `-F` being set) and is split into chars in `@F`. Then the code in `'`s is `eval`ed 13 times. This code `s`ubstitues every char (`s!.!...!`) in the input (`s///` works on `$_` by default) with either the char at the current position from `@F` (`$F[pos]`) or a space (`$"`) depending on whether or not the current value of `$-` (which starts as `0`) is equal to the value in the in the list of values, modulo `48`. This list is constructed from the 24-digit integer (`654322111000000011122345`), which represents the first set of rows in which the char should be displayed for the waveform, which is split into digits (`=~/./g`) and the second part is created in the immediately following `map` which subtracts the values from `12`, resulting in a list of 48 values that indicate where chars should be displayed. `$-` is incremented using the return from `say` (which outputs the current value of `$_` with a trailing newline) which is `1`.

# Answer
> 3 votes
## JavaScript, ~~251~~ ~~243~~ ~~224~~ ~~220~~ 217

Really simple implementation: it uses a string of characters to represent the y-position of each character on the wave (offset by `a`, which is ASCII code 97). It then iterates through all possible rows; if the y-value of the current row is the same as the y-position on the wave, it writes a character from the string. There's also a cleanup at the end to remove the row if it turned out to be completely blank.

Note that the output will appear wonky in the `alert()` window if it's not using a monospaced font, you can change it to `console.log()` to verify the output is correct.

```
s=prompt(o=[])
for(y=i=0;y<13;++y){o[i]=""
for(x=0;x<s.length;++x)o[i]+=y=="gfedccbbbaaaaaaabbbccdefghijkklllmmmmmmmlllkkjih".charCodeAt(x%48)-97?s[x]:" "
if(o[i++].trim().length<1)o.splice(--i,1)}
alert(o.join("\n"))

```

EDIT1: `++` and `--` exist.

EDIT2: Blank line removal is now done in the same loop as the rest, saving 17 characters. Didn't need those brackets either, for an extra 2 characters.

EDIT3: No need to declare the waveform as a variable, saving 4 characters.

EDIT4: As pointed out by Dom Hastings in the comments, the byte count included the carriage return as well as the newline character, updated the byte counts for all revisions to exclude the carriage return.

EDIT5: Saved 3 bytes courtesy of Dom Hastings. I haven't implemented the `o.splice` fix as this fails to remove the blank lines (on my end, at least).

# Answer
> 3 votes
## Matlab, 133, 130 bytes

The one liner:

```
s=input('');y=ceil(5.6*sin(0:pi/24:pi-.1).^.9);l=[-y y]+7;n=numel(s);t=repmat(' ',13,n);for k=1:n;t(l(mod(k-1,48)+1),k)=s(k);end;t

```

And the expanded version:

```
function f(s)
    y=ceil(5.6*sin(0:pi/24:pi-.1).^.9);l=[-y y]+7;  %// calculate the line number for each column position
    n=numel(s);                                     %// number of character in input
    t=repmat(' ',13,n);                             %// Create a blank canvas of whitespace characters
    for k=1:n
        t(l(mod(k-1,48)+1),k)=s(k);                 %// place each input character where it should be
    end
    t                                               %// force the output display

```

---

The one liner takes input from the console (`stdin`) and is 130 bytes. The expanded version replace the console input by a function definition (+1 byte) but is much more comfortable to use for the test case in a loop:

---

**Description:**

The line index of each character is calculated for a half period, then mirrored and concatenated to have a full period.
We create a blank background of whitespace character (same length as the input string. We place each character according to its position in the relevant line. If the input string is longer than one period, the `mod` (modulo) operator wraps that so we don't get out of bound when requesting the line number.

---

**Test case:**

Save the function version under `textsine.m` in your path, then run:

```
s = {'.................................................';...
    'Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It''s 100% free, no registration required.';...
    'Short text.';...
    'The quick brown fox jumps over the lazy dog'};

for txtcase=1:4
    textsine(s{txtcase,1})
end

```

will output:

```
t =

         .......
      ...       ...
    ..             ..
   .                 .
  .                   .
 .                     .
.                       .                       .
                         .                     .
                          .                   .
                           .                 .
                            ..             ..
                              ...       ...
                                 .......

t =

         ng Puzz                                         ion and                                         siasts                                          stratio
      mmi       les                                   est        an                                   thu       and                                   egi       n r
    ra              &                               qu             sw                               en              c                                r             eq
   g                                                                 e                                               o                             o                 u
  o                   C                           a                   r                           e                   d                           n                   i
 r                     o                                                                         l                     e                                               r
P                       d                       s                       s                       z                                               ,                       e
                         e                     i                         i                     z                         g                     e                         d
                                                                          t                   u                           o                   e                           .
                           G                 e                             e                 p                             l                 r
                            ol             ng                                f             g                                fe              f
                              f S       cha                                   or        min                                   rs.       00%
                                 tack Ex                                         program                                          It's 1

t =

         t.
      tex
    t
   r
  o
 h
S

t =

          brown
      ick       fox
    qu              j
                     u
  e                   m
 h                     p
T                       s

                          o
                           v
                            er
                               th       dog
                                 e lazy

```

---

if you want to test the one liner version with input from `stdin`, your input has to be entered as **one** single `string`, so you'd have to enclose your input between `'` characters. Example:

```
'Short text.'   %//   valid input
Short text.     %// INVALID input

```

---

*Thanks `Luis Mendo` for shaving up 3 bytes ;-)*

# Answer
> 2 votes
# Scala 377 characters

first cut. probably can get a better formula to translate `x` to `y`

```
(s:String)⇒s.zipWithIndex.map(t⇒(t._1,t._2,t._2%48 match{
case i if i<5⇒6-i
case 5|19⇒2
case 6|7|8|16|17|18⇒1
case i if i<16⇒0
case i if i<29⇒i%20+2
case 29|43⇒10
case 30|31|32|40|41|42⇒11
case i if i<40⇒12
case i if i>43⇒10-i%44
})).groupBy(_._3).toSeq.map{case(y,xs)⇒(""→0/:xs.sortBy(_._2)){case((p,l),(c,x,_))⇒(p+" "*(x-l-1)+c)→x}._1→y}.sortBy(_._2).map(_._1).mkString("\n")

```

# Answer
> 1 votes
# Common Lisp, 205 bytes

```
(lambda(s &aux p v o)(dotimes(r 13)(setf o 0 p v v(round(*(/ 24 pi)(+(asin(-(/ r 6)1))pi))))(when p(map()(lambda(c)(princ(if(some(lambda(k)(<= p(mod k 48)(1- v)))`(,o,(- 23 o)))c" "))(incf o))s)(terpri))))

```

## Tests

See http://pastebin.com/raw.php?i=zZ520FTU

## Remarks

Print the output line by line, computing the indices in the strings that should be printed using the inverse sine function `asin`. The output do not match exactly the expected inputs in the question, but since OP acknowledges that the example outputs are not real sine, I guess this is ok. At least, there is always only one character written for each column.

# Answer
> 1 votes
# Python 2, 172 bytes

This isn't as good as Alex L's answer, but it's pretty close. Takes input from standard input and works best in a `.py` file.

```
l=map(int,bin(9960000)[2:]);l+=[-c for c in l];s=6;o=[];i=9
for c in raw_input():b=[' ']*13;b[s]=c;o+=[b];s+=l[i%48];i+=1
print''.join(sum(zip(*o+['\n'*13])[::-1],())[:-1])

```

I decided to build the output transposed (each column is a row) and then transpose the result, since in python the transpose of a matrix is `map(*m)`.

* `l`: The binary representation of `9960000` (after chopping off the `"0b"` from `bin`) is `100101111111101001000000`. This is the "step" of the sine wave each column, starting at the very last character of the very lowest point. I copy this list, negate each number, and tack it onto the end of itself to form what is effectively a derivative of the function.
* `s`: This is the variable that keeps track of which row (column in the transpose) the next character gets inserted into.
* `o`: End output, transposed
* `i`: Keeps track of sine wave period. Starts at 9 since `l` is shifted slightly.

In the `for` loop, I create a list of 13 spaces (I was using bytearrays but lists of characters turn out to have a shorter print statement), then replace the `s`th character with the input character. Append `b` to the end of `o`, add the appropriate step to `s`, and increment `i`.

I had hoped the `print` statement would be as simple as `\n'.join(*zip(o))`, but no such luck. `zip(*o+['\n'*13])[::-1]` appends a column of newlines and then reverses and transposes the whole thing (without the reversing, the sine wave is upside down), `sum(...,())` concatenates the tuples together into one tuple of characters, and then `''.join(...)` concatenates the characters and prints it.

Other things I tried were making a 12-character array of spaces and inserting the new character into the appropriate place, and replacing `l+=[-c for c in l];` with some sort of math with some sort of multiplication of `1` and `-1` with the result of indexing into `l`, but nothing I could come up with ended up being shorter.

# Answer
> 0 votes
# Mathematica, 131 bytes

```
i=[input string];c=Characters@i;l=Length@c;StringJoin@Riffle[StringJoin@@@SparseArray[Table[{7-Round[6 Sin[.13(x-1)]],x},{x,l}]->c,{13,l}," "],"\n"]

```

That's 131 characters, including the three for `i=foo;`. That seemed a reasonable way to take the input; I could have put it straight into the definition of `c` and saved a few strokes, but that feels unfair.

It's pretty straightforward -- almost even readable. It splits the string into a list of characters, and then puts those characters into a sparse array at the positions determined from the `Table` (any spot in the array not given a character defaults to a space). The lines are assembled separately, then newlines sprinkled between them. The final StringJoin stitches it all up.

**NB:** Like some other solutions, this may not actually be valid because it produces a real sinusoid rather than the (beautiful) handcrafted example.

## Tests:

```
(*i=Programming Puzzles...*)
         ng Puzz                                          on and                                          iasts                                           tration
       mi       le                                     sti       a                                      us      and                                     is        r
     am           s                                   e           ns                                  th            c                                 eg           eq
    r               &                               qu              we                              en               o                               r               u
  og                  C                                               r                                               d                            o                  ir
 r                     o                          a                                               e                    e                          n                     e
P                       d                       s                       si                       l                       g                                               d
                         e                     i                          t                    zz                         o                     ,                         .
                           G                                               e                  u                            lf                 ee
                            o               ge                               f               p                               e               r
                             lf           an                                  or           g                                  rs            f
                                St      ch                                       p      min                                     .        0%
                                  ack Ex                                          rogram                                          It's 10
(*i=.... ...*)
         .......
       ..       ..
     ..           ..
    .               .
  ..                 ..
 .                     .
.                       .                       .
                         ..                    .
                           .                  .
                            .               ..
                             ..           ..
                               ...      ..
                                  ......
(*i= Short text.*)
         t.
       ex
      t
    t
  or
 h
S

(*i=The quick...*)
          brown
       ck       fo
     ui           x
    q               j
  e                  um
 h                     p
T                       s
                          o
                           v
                            e
                             r            g
                               the      do
                                   lazy

```

---
Tags: code-golf, ascii-art, string
---