title: Output the nth 'boring' number

text:
# Question
Title: Output the nth 'boring' number
There are 9 main types of numbers, if you categorise them by the properties of their factors. Many numbers fall into at least one of these categories, but a few don't. The categories are as follows:

* Prime - no integer divisors other than itself and one
* Primitive abundant - A number \\$n\\$ whose factors (excluding \\$n\\$) sum to more than \\$n\\$, **but** for any factor \\$f\\$ of \\$n\\$, the sum of the factors of \\$f\\$ sum to *less than* \\$f\\$
* Highly abundant - A number \\$n\\$ whose factors (*including* \\$n\\$) sum to more than that of any previous number
* Superabundant - A number \\$n\\$, such that the sum of the factors of \\$n\\$ (including \\$n\\$) divided by \\$n\\$ is greater than the sum of factors of \\$g\\$ over \\$g\\$ for any value \\$0\<g\<n\\$
* Highly composite - A number \\$n\\$ which has more factors than \\$g\\$, where \\$g\\$ is any number such that \\$0\<g\<n\\$
* Largely composite - same as highly composite, but \\$n\\$ can have also have *equally as many* factors as \\$g\\$
* Perfect - A number that is exactly equal to the sum of its factors (excluding itself)
* Semiperfect - A number that can be made by summing up two or more of its factors (excluding itself)
* Weird - A number \\$n\\$ that is not semiperfect, but which's divisors sum to more than \\$n\\$.

A so-called 'boring number' is any positive, non-zero integer which does not fit into any of these categories.

Your job is to create the shortest possible program which can, given a positive number \\$n\\$, outputs the \\$n\\$th boring number.

*Note: I am aware there are more categories, but I wanted to avoid using mutually exclusive ones (such as deficient and abundant), because then every number would fall into one of them.*

# Rules

* Standard loopholes apply; standard I/O methods apply.
* All inputs will be positive, non-zero integers, a single output is expected.
* `n` can be 0- or 1- indexed.
* This is , so shortest answer in bytes wins.

# Tests

The first 20 boring number are:

`9, 14, 15, 21, 22, 25, 26, 27, 32, 33, 34, 35, 38, 39, 44, 45, 46, 49, 50`

# Answer
# JavaScript (ES6),  ~~226 220~~  209 bytes

*Saved 11 bytes thanks to @HermanL*

Input is 1-indexed.

```
f=(x,n=m=c=1,D=k=>k?n%k?D(k-1):[k,...D(k-1)]:[],S=a=>s=eval(a.join`+`))=>(S(a=D(n))>m?m=s:0)|(s=a.length)<3|(s<c?0:c=s)|a.reduce((a,x,i)=>i?[...a,...a.map(y=>[...y,x])]:a,[[]]).some(a=>S(a)>=n)||--x?f(x,n+1):n

```

Try it online!

Optimizations are based on the following properties:

* All primitive abundant numbers are either semiperfect or weird.
* All highly composite numbers are largely composite.
* All superabundant numbers are highly abundant.
> 4 votes

# Answer
# 05AB1E, ~~43~~ ~~39~~ ~~36~~ ~~33~~ 24 bytes

```
∞ʒpyLRÑOć‹PyÑ¨©æOyå®Oy›O_}Iè

```

-4 bytes thanks to *@Mr.Xcoder*.
-12 bytes thanks to *@Grimy* (of which -5 are because "*Highly composite numbers higher than 6 are also abundant numbers*", and -4 because "*'The sum of N's divisors is greater than N' is equivalent to 'The sum of some subset of N's divisors is greater than N'*").

0-indexed.

Try it online or output the first \\$n\\$ values of the sequence.

**Explanation:**

```
∞           # Push an infinite list of positive integers: [1,2,3,...]
 ʒ          # Filter it by, leaving only the integers `y` which are truthy for:
  p         #  1) Check if `y` is a prime
  yL        #  Create a list in the range [1, `y`]
    R       #  Reverse the list to range [`y`, 1]
     Ñ      #  Get the divisors of each integer
      O     #  Sum the inner lists together
       ć    #  Extract the head; pop and push remainder-list and head
        ‹P  #  2) Check if each value in the remainder-list is smaller than the head
  yÑ        #  Get the divisors of `y`
    ¨       #  Remove the last item (`y` itself)
     æ      #  Powerset; get all possible combinations of these divisors
            #  (this includes both an empty list and all divisors of `y`)
      O     #  Sum each inner combination-list
       y@à  #  3) Check if any sum is larger than or equal to `y`
  O_        #  And only leave the integers in the filter which are falsey for all checks
}Iè         # After the filter: Index the input-integer into the filtered list

```

1) covers the check for Prime
2) covers the checks for Highly Abundant, Superabundant, Largely composite and Highly composite
3) covers the checks for Perfect, Semiperfect, Weird, and Primitive Abundant
> 2 votes

# Answer
# Java, 208 bytes

Input is 1-indexed.

```
interface a{static void main(String[]a){int i=0,n=0,x=1,z=1,j,u,f,b;for(;n<new Integer(a[0]);n+=f>=i?0:1/++b){for(i+=j=u=f=b=1;++j<i;)if(i%j<1){f+=j;b=0;u++;}x=f>x--?b=f:x;z=u>=z?b=u:z;}System.out.print(i);}}

```

in readable form:

```
interface a
{
    static void main(String[]a)
    {
        int i=0,n=0,x=0,z=0,j,u,f,b;
        for(;n<new Integer(a[0]);n+=f>=i?0:1/++b)   //checks perfect, semiperfect, weird, and p. abundant numbers
        {
            for(i+=j=u=f=b=1;++j<i;)if(i%j<1){f+=j;b=0;u++;}    //checks prime numbers
            x=f>x--?b=f:x;              //checks highly abundant and superabundant numbers
            z=u>=z?b=u:z;               //checks largely and highly composite numbers
        }
        System.out.print(i);
    }
}

```
> 1 votes

# Answer
# Jelly, 28 bytes

```
Æd,Æs)Ṫ_$<Ø.S;Æṣ<$;Ẓ¬$Ạµ#}1Ṫ

```

Try it online!

A full program taking a single argument N and outputting the 1-indexed boring number.

Takes advantages of the optimisations noted in the description of @Arnauld’s answer, but not based on the JavaScript code.

### Explanation

```
Æd,Æs)Ṫ_$<Ø.S;Æṣ<$;Ẓ¬$Ạµ#}1Ṫ

                       µ#}1  | Run the following for each number from 1 increasing in steps of 1 until we have as many true values as indicated by the argument, then return the numbers for which it was true:
     )                       | - For each number from 1 up to the currently tested number:
Æd                           |   - Count of divisors
  ,                          |   - Paired with:
   Æs                        |     - Sum of divisors
      Ṫ_$                    | - Tail (divisor count and sum for current number) minus divisor count and sum for all smaller numbers
         <Ø.                 | - Check if each [divisor count difference, divisor sum difference] < [0, 1]
            S                | - Sum (will sum the checks of divisor count difference and divisor sum difference separatelt)
             ;               | - Concatenate to:
              Æṣ<$           |   - Whether proper divisor sum less than current number
                  ;          | - Concatenate to:
                   Ẓ¬$       |   - Whether number is not prime
                      Ạ      | - All of these (only true for boring numbers)
                           Ṫ | Finally, take the tail (the requested boring number)

```

In contrast to many of the Jelly code explanations I’ve written, this almost goes from left-to-right!
> 0 votes

# Answer
# Python 2, 155 bytes

```
n=input();k=D=N=0
while n:k+=1;L=[d for d in range(1,k+1)if k%d<1];S=sum(L);W=len(L);K=S-k;x=K<2or S>D or W>=N or K>=k;n-=1-x;N=max(W,N);D=max(D,S)
print k

```

Try it online! first n entries
> 0 votes

---
Tags: code-golf, sequence
---


# Question
Title: Generating all Character possibilities with two characters
# Introduction

So the Challenge is to give out all combinations with two Inputs. The length of the string is also optional and you should be able to edit this.

I've selected this channel because I thought it would be very easy to do it "normally" but the challenge itself could be very interesting. I had to create that for one of our employee to make a list with product numbers.

I quickly searched the site and I didn't found any other Challenges like this.

# Challenge

So the input doesn't have to be edited so you can just take the binary system \[0,1\]. But you have to set the length of the string or char of the output.

You can give out all the numbers in a file. You can decide the name and also the file type.

The Shortest program in characters wins.

# Example Input and Output

Input:

> 3

Output example.txt:

```
000
001
010
100
101
110
111
011

```

Input:

> 2

Output example.txt:

```
00
01
10
11

```

# Answer
# 05AB1E, 3 bytes

```
TIã

```

Try it online or verify a few more test cases.

**Explanation:**

```
T    # Push 10
 Iã  # Take the cartesian product of "10" repeated the input amount of times
     # (and output the resulting list implicitly as result)

```
> 1 votes

# Answer
# Python 2, 46 bytes

```
lambda n:map(('{:0%db}'%n).format,range(1<<n))

```

Try it online!
> 0 votes

---
Tags: code-golf, binary
---


title: Is this number a palindrome?

text:
# Question
Title: Is this number a palindrome?
## Input

A single integer in your language's preferred format, e.g `int` or an array of digits are all acceptable.

## Output

A truthy or falsely value, depending on whether the given number is palindromic (same forwards and backwards)

## Rules

* Numbers will always be positive, at least two digits long.
* This is , so lowest O(n) time complexity wins.

# Test cases

* 123454321 - true
* 296296 - false
* 296692 - true
* 5499456 - false
* 0 - false/error/any value

# Answer
# APL (Dyalog Unicode), *O*(1)

`⊃∘'111111111110`… …`10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'`

Anonymous tacit prefix function.

Try it online!

Simply picks the result from a pre-compiled list.
> 6 votes

# Answer
# Java, complexity: \\$O(\lfloor\log\_{10}(n) + 1\rfloor)\\$

```
boolean f(int n){
  int reverse = 0;
  //int debugIterations = 0;
  for(int palindrome = n; palindrome != 0; palindrome /= 10){
    //debugIterations++;
    int lastDigit = palindrome % 10;
    reverse = reverse * 10 + lastDigit;
  }
  //System.out.println("Debug iterations: "+debugIterations);
  return n == reverse;
}

```

Loops once for every digit in the input-number. Pretty straight-forward implementation tbh..

Try it online.
> 3 votes

# Answer
# Java, O(1)

```
boolean f(int n){
  if (n <= 0 || n >= 16777216) throw new Error(n+" is not a valid input!");
  int reverse = n/10000000%10*1 + n/1000000%10*10 + n/100000%10*100 + n/10000%10*1000 + n/1000%10*10000 + n/100%10*100000 + n/10%10*1000000 + n/1%10*10000000;
  int len = (int) Math.log10(n);
  reverse/= Math.pow(10, 7-len);
  return reverse == n;
}

```

Try it online!

Kevin Cruijssen's answer, unrolled for 24-bit numbers.
> 1 votes

# Answer
# APL+WIN, O(1)

Thanks to Adam for suggested changes to my original code and his explanation - see the comments section.

Prompts for input of integer.

```
 17=+/(⌽17↑n)=¯17↑n←⍕⎕

```

Try it online!
> 0 votes

---
Tags: number, integer, palindrome, fastest-algorithm
---


title: Find the closest HTML colour name

text:
# Question
Title: Find the closest HTML colour name
## Input

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

## Output

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

## Examples

> `FF04FE`: `magenta`
>
> `FFFFFF`: `white`
>
> `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**)

## Rules

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

## Colors

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

```
Color Name,HEX
Black,#000000
Navy,#000080
DarkBlue,#00008B
MediumBlue,#0000CD
Blue,#0000FF
DarkGreen,#006400
Green,#008000
Teal,#008080
DarkCyan,#008B8B
DeepSkyBlue,#00BFFF
DarkTurquoise,#00CED1
MediumSpringGreen,#00FA9A
Lime,#00FF00
SpringGreen,#00FF7F
Aqua,#00FFFF
Cyan,#00FFFF
MidnightBlue,#191970
DodgerBlue,#1E90FF
LightSeaGreen,#20B2AA
ForestGreen,#228B22
SeaGreen,#2E8B57
DarkSlateGray,#2F4F4F
DarkSlateGrey,#2F4F4F
LimeGreen,#32CD32
MediumSeaGreen,#3CB371
Turquoise,#40E0D0
RoyalBlue,#4169E1
SteelBlue,#4682B4
DarkSlateBlue,#483D8B
MediumTurquoise,#48D1CC
Indigo,#4B0082
DarkOliveGreen,#556B2F
CadetBlue,#5F9EA0
CornflowerBlue,#6495ED
RebeccaPurple,#663399
MediumAquaMarine,#66CDAA
DimGray,#696969
DimGrey,#696969
SlateBlue,#6A5ACD
OliveDrab,#6B8E23
SlateGray,#708090
SlateGrey,#708090
LightSlateGray,#778899
LightSlateGrey,#778899
MediumSlateBlue,#7B68EE
LawnGreen,#7CFC00
Chartreuse,#7FFF00
Aquamarine,#7FFFD4
Maroon,#800000
Purple,#800080
Olive,#808000
Gray,#808080
Grey,#808080
SkyBlue,#87CEEB
LightSkyBlue,#87CEFA
BlueViolet,#8A2BE2
DarkRed,#8B0000
DarkMagenta,#8B008B
SaddleBrown,#8B4513
DarkSeaGreen,#8FBC8F
LightGreen,#90EE90
MediumPurple,#9370DB
DarkViolet,#9400D3
PaleGreen,#98FB98
DarkOrchid,#9932CC
YellowGreen,#9ACD32
Sienna,#A0522D
Brown,#A52A2A
DarkGray,#A9A9A9
DarkGrey,#A9A9A9
LightBlue,#ADD8E6
GreenYellow,#ADFF2F
PaleTurquoise,#AFEEEE
LightSteelBlue,#B0C4DE
PowderBlue,#B0E0E6
FireBrick,#B22222
DarkGoldenRod,#B8860B
MediumOrchid,#BA55D3
RosyBrown,#BC8F8F
DarkKhaki,#BDB76B
Silver,#C0C0C0
MediumVioletRed,#C71585
IndianRed,#CD5C5C
Peru,#CD853F
Chocolate,#D2691E
Tan,#D2B48C
LightGray,#D3D3D3
LightGrey,#D3D3D3
Thistle,#D8BFD8
Orchid,#DA70D6
GoldenRod,#DAA520
PaleVioletRed,#DB7093
Crimson,#DC143C
Gainsboro,#DCDCDC
Plum,#DDA0DD
BurlyWood,#DEB887
LightCyan,#E0FFFF
Lavender,#E6E6FA
DarkSalmon,#E9967A
Violet,#EE82EE
PaleGoldenRod,#EEE8AA
LightCoral,#F08080
Khaki,#F0E68C
AliceBlue,#F0F8FF
HoneyDew,#F0FFF0
Azure,#F0FFFF
SandyBrown,#F4A460
Wheat,#F5DEB3
Beige,#F5F5DC
WhiteSmoke,#F5F5F5
MintCream,#F5FFFA
GhostWhite,#F8F8FF
Salmon,#FA8072
AntiqueWhite,#FAEBD7
Linen,#FAF0E6
LightGoldenRodYellow,#FAFAD2
OldLace,#FDF5E6
Red,#FF0000
Fuchsia,#FF00FF
Magenta,#FF00FF
DeepPink,#FF1493
OrangeRed,#FF4500
Tomato,#FF6347
HotPink,#FF69B4
Coral,#FF7F50
DarkOrange,#FF8C00
LightSalmon,#FFA07A
Orange,#FFA500
LightPink,#FFB6C1
Pink,#FFC0CB
Gold,#FFD700
PeachPuff,#FFDAB9
NavajoWhite,#FFDEAD
Moccasin,#FFE4B5
Bisque,#FFE4C4
MistyRose,#FFE4E1
BlanchedAlmond,#FFEBCD
PapayaWhip,#FFEFD5
LavenderBlush,#FFF0F5
SeaShell,#FFF5EE
Cornsilk,#FFF8DC
LemonChiffon,#FFFACD
FloralWhite,#FFFAF0
Snow,#FFFAFA
Yellow,#FFFF00
LightYellow,#FFFFE0
Ivory,#FFFFF0
White,#FFFFFF

```

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

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

```

Explanation:

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

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

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

```

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

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

Try it online!
> 17 votes

# Answer
# Node.js, 1488 bytes

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

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

```

Try it online!

### How?

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

```
"black0navy3KdarkblueBmediumblue1Ublue1EdarkgreenJK1green5J4(…)lightyellow68ivoryGwhiteF"

```

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

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

```

### Commented

```
v =>                            // v = input
  ( require('zlib')             // using zlib,
    .inflateRawSync(            // inflate the
      Buffer(                   //   buffer obtained by
        'TVRbm(…)Pw',           //     converting this string
        'base64'                //     encoded in base-64
      )                         //
    ) + ''                      // and coerce it back to a string
  ).replace(                    // on which we invoke replace():
    m =                         //   initialize m to a non-numeric value
    /([a-z]+)([^a-z]+)/g,       //   for each color encoded as ...
    (_, s, d) =>                //   ... s = name, d = delta in base-36:
      [e = 0, 8, 16]            //     using x = 0 for blue, 8 for green and 16 for red,
      .map(x =>                 //     compute the error e:
        e +=                    //       add to e:
          Math.abs(             //         the absolute value of the difference between
            (v >> x & 255) -    //           the component of the target color
            (t >> x & 255)      //           and the component of the current color
          ),                    //
        t += parseInt(d, 36)    //       start by adding the delta to t
      ) | e > m ||              //     end of map(); if e is less than or equal to m:
        (o = s, m = e),         //       update o to s and m to e
    t = 0                       //   start with t = 0
  ) && o                        // end of replace(); return o

```
> 14 votes

# Answer
# Jelly, ~~1015~~ 914 bytes

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

```

Try it online!

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

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

## Explanation

### Helper link

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

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

```

### Main link

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

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

```

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

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

```

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

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

# Answer
# Wolfram Language (Mathematica), 164 bytes

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

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

```

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

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

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

```

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

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

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

```

Try it online!

Commented:

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

```

I had to

```
npm install color-name

```

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

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

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

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

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

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

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

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

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

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

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

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

# Answer
# JavaScript (Firefox), 1050 bytes

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

```

```
f =

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

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

Third JavaScript language in this question now...

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

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

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

# Answer
# 05AB1E, 1175 bytes

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

```

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

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

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

**Explanation:**

First we generate all the color-strings:

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

```

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

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

```

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

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

```

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

* `.•ŒRǝ...Ð:8•` is `"chiffon lavenderblush papayawhip ... cyan turquoise steelblue"`
* `“ƒÏª©–°0‡—...‡Ž0ŠÛØ‰„¸“` is `"black navy dark0 blue ... light0 yellow ivory white"`
* `•zÑÄ...C±;•` is `199...791`
* `•Oи¤•` is `1579378`
* `•zÑÄ...C±;••Oи¤•в` is `[128,11,66,...,224,16,15]`
> 1 votes

---
Tags: code-golf, color
---


title: Keep my Trip Cool!

text:
# Question
Title: Keep my Trip Cool!
## Challenge

Walking around Marks and Spencers, I noticed that they had air conditioning units placed randomly around the shop. Wanting to keep cool, I wondered what was the easiest way to move around the whole shop without being away from an air conditioning unit for too long.

Given a map, you must find a way to travel around the whole map keeping the distance from an air conditioning unit as short as possible (even if the AC unit is on the other side of a wall).

## Map

The map may be supplied in any way you like and uses the following symbols:

```
+ is a corner of a wall
| is a east/west facing wall
- is a north/south facing wall
X is an air conditioning unit
S is the start and end point

```

An example map would be:

```
+------S---+
|   X      |
| ---+-+ X |
|    |X|   |
| ---+ +---+
|   X      |
+----------+

```

or

```
+---+--+
| X |  |
|   |  +-----+------+
|   | X      | X    |
|     ---+       |  S
|   |    |  X    |  |
|   |  +-+-------+--+
| X    |
+------+

```

Travelling around the whole map means passing through every empty space and air conditioner. You cannot travel through a wall and may only travel orthogonally. A map may not always be rectangular.

Keeping the distance as short as possible from an AC unit is the sum over all time steps.

Passing through means entering and leaving.

You may output the path in any way you like. Examples include:

* Outputting the map with the path included
* Outputting the path as a succession of compass points (e.g. `NNSESW`)

# Answer
> 1 votes
# PowerShell for Windows, ~~376~~ 367 bytes

Like a lazy man, I don't go to every shelf, I move from air conditioner to air conditioner in a store. I believe I traveled all over the store visiting every air conditioner in it.

```
$f={param($m,$d,$o=@{})$w=(($l=$m-split"
")|% le*|sort)[-1]
$m=($l|% *ht $w)-join"
"
if(!$o.$m-or$o.$m-ge$d-and$m-match'(?s)X.*S|S.*X'){$o.$m=$d++
$n=-split")X(S )X(.{$w}S S)X( S.{$w})X("|%{sls "(?s)^(.*$_.*)$" -inp $m -a|% m*|%{($_.Groups-replace'S',' ')[1,2]-join'S'}}
$d=(($n+,($m-replace"(?s)(?<=S(.{$w})?) | (?=(.{$w})?S)",'S')*!$n)|%{&$f $_ $d $o}|sort)[0]}+$d}

```

Try it online!

Unrolled:

```
$f={
    param($map,$distance,$o=@{})
    $lines = $map-split"`n"
    $width = ($lines|% length|sort)[-1]
    $map = ($lines|% padRight $width)-join"`n"                              # to rectangle

    if(!$o.$map -or $o.$map-ge$distance -and $map-match'(?s)X.*S|S.*X'){
        $o.$map = $distance++                                               # store a map to avoid recalculations
        $n = -split")X(S )X(.{$width}S S)X( S.{$width})X("|%{               # search a nearest X in 4 directions
            select-string "(?s)^(.*$_.*)$" -InputObject $map -AllMatches|% Matches|%{
                ($_.Groups-replace'S',' ')[1,2]-join'S'                     # start a new segment (reset all S and replace the nearest X by S)
            }
        }
        $stepMore = $map-replace"(?s)(?<=S(.{$w})?) | (?=(.{$w})?S)",'S'
        $n += ,$stepMore*!$n                                                # add a step if X was not found
        $distance=($n|%{&$f $_ $distance $o}|sort)[0]                       # recursive repeat
    }

    +$distance
}

```

---
Tags: code-golf, ascii-art, path-finding
---


title: Golf my iteration function

text:
# Question
Title: Golf my iteration function
Here is my ungolfed Ruby code for a function I want to try and golf:

```
Iter =-> k {
    str = ""
    (0..k).map{|m| str += "-> f#{m} {"}
    str += "f#{k}.times{f1 = f0[f1]};f1"
    (2..k).map{|m| str += "[f#{m}]"}
    eval(str + "}" * (k+1))
}

```

The best I can do to golf this is essentially shortening variable names, removing spaces, and rearranging the code to reduce the amount of loops:

```
I=->k{s="f#{k}.times{f1=f0[f1]};f1"
(2..k).map{|m|s+="[f#{m}]"}
(0..k).map{|m|s="->f#{k-m}{"+s+?}}
eval s}

```

Try it online!

This function can be compacted so that it avoids a lot of defining new functions. You can think of it like this:

$$\operatorname{Iter}(k;f\_0,f\_1,\dots,f\_k)=f\_0^{f\_k}(f\_1)(f\_2)(f\_3)\dots(f\_k)$$

where

$$f^n(x)=\underbrace{f(f(\dots f(}\_nx)\dots))$$

denotes function iteration. The types of arguments are given as:

$$\operatorname{Iter}(\text{int};\dots,(\text{int}\mapsto\text{int})\mapsto(\text{int}\mapsto\text{int}),\text{int}\mapsto\text{int},\text{int})$$

That is, the last argument is an integer, and each previous argument maps from T to T, where T is the type of the next argument on the right.

It is true that accepting all arguments at once would allow me to golf the above code further:

```
I=->k,*a{a[-1].times{a[1]=a[0][a[1]]};(2..k).map{|m|a[1]=a[1][a[m]]};a[1]}

```

However, the issue is that I need to curry this function. This way, I may treat objects such as

$$\operatorname{Iter}(k)(f\_0)$$

as their own object, and thus be able to pass this into Iter(k) to get things such as

$$\operatorname{Iter}(k)(\operatorname{Iter}(k)(f\_0))$$

As a specific example of what this function does, we have

\begin{align}\operatorname{Iter}(2)(\operatorname{Iter}(1))(x\mapsto x+1)(2)&=\operatorname{Iter}(1)(\operatorname{Iter}(1)(x\mapsto x+1))(2)\\\&=\operatorname{Iter}(1)(x\mapsto x+1)(\operatorname{Iter}(1)(x\mapsto x+1)(2))\\\&=\operatorname{Iter}(1)(x\mapsto x+1)(2+1+1)\\\&=\operatorname{Iter}(1)(x\mapsto x+1)(4)\\\&=4+1+1+1+1\\\&=8\end{align}

> I'm interested in seeing if this can be golfed down further, with the restriction that the arguments must be curried in the order provided.

# Answer
# Ruby, 87 bytes

```
I=->k{eval ("->f%d{"*-~k+"f%d.times{f1=f0[f1]};f1"+"[f%d]"*~-k+?}*-~k)%[*0..k,k,*2..k]}

```

Try it online!
> 2 votes

# Answer
# Ruby, ~~94~~ 96 bytes

Using loops to do concatenations that followed such a simple pattern felt cumbersome, so I utilized the creative use of `join` instead, further golfed by the fact that `array*str` is equivalent to `array.join(str)`

*+2 bytes to fix a typo I made that just so happened to return the same result on the test example by chance.*

```
I=->k{eval"->f#{[*0..k]*'{->f'}{f#{k}.times{f1=f0[f1]};f1#{"[f#{[*2..k]*'][f'}]"if k>1}"+?}*-~k}

```

Try it online!
> 3 votes

---
Tags: code-golf, math, tips, recursion, ruby
---


# Question
Title: Report divisibility with arithmetic integer operations only
Given two numbers, the first is greater than the second, check whether the first number is divisible by the second without a remainder. If divisible, answer `"yes"`(or any other string), otherwise `"no"(or any other string you like)`.

**Conditions:** You cannot use conditional operators, loops, arrays, bitwise operations, functions and methods. You can use variables, all arithmetic integer operations (that is, integer division), even the operation of taking the remainder of a division.

Numbers can range from 1 to 1,000,000. Maximum running time is 1 second.

You can of course write in any language, but here is my non-golfed solution in C++:

> ```
> int main() {
>   int a,b; cin >> a >> b;
>   int c = a%b;
>   int n = (c+1-(c-1)*((2*(c-1)+1)%2))/2;
>   int y = 121, e = 101, s = 115;
>
>   cout << (char)(y-11*n) << (char)(e+10*n) << (char)(s-83*n) << endl;
> }
> ```

# Answer
# 05AB1E, 1 byte

```
Ö

```

Try it online!

Outputs 1 if divsible 0 if not

---

### Old version with string must be Yes or No

# 05AB1E, ~~13~~ ~~12~~ 10 bytes

```
Ö'…Ü„nor.D

```

---

```
Ö              // Test to see if they are divisible
 '…Ü           // The string yes
     „no      // the string no
         r     // reverse the stack
          .D   // push whether they are divisible copies of "yes"
               // Implicitly output the result

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 17 bytes

Takes input as `(a)(b)`. Returns `"Y"` for *yes* or `"undefined"` (as a string) for *no*.

```
a=>b=>"Y"[a%b]+''

```

Try it online!

---

# JavaScript (ES6), 50 bytes

Takes input as `(a)(b)`. Returns `"yes"` or `"no"`, as per the original rules.

```
a=>b=>(22724-21872*((2*(a%b-1)+1)%2)).toString(36)

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~17~~ 3 bytesSBCS

Anonymous tacit infix function. Takes lesser and greater numbers as left and right arguments. Prints the string `"0"` if divisible and `"1"` if not.

```
1⌊|

```

Try it online!

`|` division remainder when dividing right argument by left argument (gives `0` for divisible or strictly positive integer for non-divisible)

`1⌊` the minimum of that and 1 (gives `0` for divisible or `1` for non-divisible)
> 1 votes

# Answer
# Runic Enchantments, 6 bytes

```
0ii%p@

```

Try it online!

Outputs 1 if divisible 0 if not.

Determines 0/1-ness by raising 0 to the power of the remainder, which returns 0 for all `x` except 0 (due to the indeterminate nature of 00 having been decided to be 1).

### Version with string output

# Runic Enchantments, 20 bytes

```
10ii%p-4´36*6X+d-E@

```

Try it online!

Utilizes the word dictionary to convert from a 0/1 value to the strings "yes" and "no" by multiplying the result by 436 and adding 47 (ok, it adds 60 and subtracts 13; the byte cost is ironically the same either way: `4X7++` vs. `6X+d-` vs. `4´7+`).

May be invalid due to using an array? There is certainly no array *in the submission code* but rather in the the interpreter due to how `E` is executed when the top of the stack is not a string.
> 0 votes

# Answer
# Befunge-98 (FBBI), 6 bytes

```
%1\k0.

```

Arguments should be pushed onto the stack, and requires the current IP delta to be (1,0). Prints `1`  if divisible and `0`  if not.

Try it online! Link includes I/O boilerplate.
> 0 votes

---
Tags: code-golf, decision-problem, restricted-source, division, restricted-time
---


title: Transpose columns in table

text:
# Question
Title: Transpose columns in table
Let's say you've got a table of data:

```
meter_id date   0000 0600 1200 1800
0        030915 10   20   30   40
1        030915 15   7    49   2

```

where the last four columns are meter readings at different times. You want to output

```
meter_id date   time reading
0        030915 0000 10
0        030915 0600 20

```

etc.

Your input and output will *not* have headers, unlike in this example. The set of columns you'll transpose will be provided as numeric arguments to your program, from 1 onwards. Input is stdin and output is stdout.

So here's an example of it actually being used.

```
$ ./tpose 3 4 5 6

```

Stdin:

```
0        030915 10   20   30   40
1        030915 15   7    49   2

```

Stdout:

```
0       030915  3       10
0       030915  4       20
0       030915  5       30
0       030915  6       40
1       030915  3       15
1       030915  4       7
1       030915  5       49
1       030915  6       2

```

The third column contains values from 3 to 6. This is because the reading is from columns 3 to 6 from the input table.

Happy golfing.

# Answer
> 3 votes
# kdb k, 101 bytes

```
1@"\n"/:{"\n"/:{" "/:(r@&{~#&x=a}'!#r),(,$1+a@x),,c@x}'!#c::(r::" "\:x)@a::-1+.:'.z.x}'-1_"\n"\:0::0;

```

**Me:** *(reads the word "transpose" in the title)* K will be perfect for this! It'll kick everything else's hind!

*20 minutes and 101 bytes later*

**Me:** Idiot.

# Answer
> 2 votes
# Ruby, ~~88~~ 84 bytes

Input is tab-separated. Annoyingly, Ruby `gets` pulls from files whose names match those from `ARGV`, but those don't exist so the program errors out. To work around this, I have to use `STDIN.gets` to get the actual correct input.

-4 bytes by remembering that I don't actually need to use `scan` since I'm only matching the pattern once per line anyways, so `=~` for a single regex match saves bytes.

```
($_=~/(\d+	\w+	)(.*)/;i=-1;puts$2.split.map{|s|"#$1#{$*[i+=1]}	"+s})while STDIN.gets

```

Try it online!

# Answer
> 1 votes
# Haskell (195 bytes)

```
import System.Environment
main=do s<-getArgs>>=return.map(\a->read a-1);interact$unlines.map unwords.t s.map words.lines
t g r=[[a!!j|j<-[0..length a-1],not$j`elem`g]++show(j+1):[a!!j]|a<-r,j<-g]

```

Ungolfed Haskell (398 bytes):

```
import System.Environment
import Prelude

main = do js <- getArgs >>= return . map (\a -> read a - 1)
          interact $ unbr . (`tpose` js) . br

br = map words . lines

xs `excludingFrom` es = [xs !! j | j <- [0..length xs - 1], not $ j `elem` es]

tpose rows js = [row `excludingFrom` js ++ [show (j+1)] ++ [row !! j] | row <- rows, j <- js]

unbr = unlines . map (foldr1 $ \t a -> t++"\t"++a)

```

# Answer
> 1 votes
# Perl 5, 87 bytes

```
perl -E'while(<STDIN>){@f=(0,split);@i=0..$#f,@i[@ARGV]=0;say"@f[grep$_,@i] $_ $f[$_]"for@ARGV}'

```

# Answer
> 1 votes
# PHP, 90 bytes

```
while($r=fgetcsv(STDIN,0,' '))foreach($argv as$a)if($a|0)echo"$r[0] $r[1] $a {$r[$a-1]}
";

```

Input and output with single space delimiter.

Try it online!

# PHP, 109 bytes

```
while($r=preg_split("/\s+/",fgets(STDIN),0,1))foreach($argv as$a)if($a|0)echo"$r[0]\t$r[1]\t$a\t{$r[$a-1]}
";

```

Or with I/O exactly as shown above, using fixed width columns.

Try it online!

# Answer
> 1 votes
# APL (Dyalog Unicode), 56 bytesSBCS

Anonymous prefix lambda. Takes column numbers for "transposition" as right argument and prompts via stdin for filename of table.

```
{(t[;⍵~⍨⍳≢⍉t]⌿⍨≢⍵),(⍪,⍨⍵⍴⍨≢),t[;⍵]⊣t←↑(∊∘⎕D⊆⊢)¨⊃⎕NGET⍞1}

```

Try it online!

`{``}` "dfn"; right argument (column numbers) is :

`⍞1` prompt for file name from stdin and juxtapose with `1` (indicating that we want a list of strings)
`["tpose",1]`

`⎕NGET`**get** the **n**ative file's (content,encoding,newline)
`[["0 030915 10 20 30 40","1 030915 15 7 49 2"],"UTF-8-NOBOM",[10]]`

pick the first of those (content)
`["0 030915 10 20 30 40","1 030915 15 7 49 2"]`

`(` apply the following tacit function to each line:

the characters that are members
of
`⎕D` the set of **d**igits
`[[1,0,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1],[1,0,1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1]]`

indicate the sub-partitions of

the line
`[["0","030915","10","20","30","40"],["1","030915","15","7","49","2"]]`

up the rank by mixing the list (rank 1) of lists into a matrix (rank 2)
`[["0","030915","10","20","30","40"],`
`["1","030915","15","7" ,"49","2" ]]`

`t←` assign that to `t` (for **t**able)

discard that in favour of

`t[;⍵]` all rows of the subset of columns of `t` enumerated in the argument
`[["10","20","30","40"],`
`["15","7" ,"49","2" ]]`

`,` ravel (flatten that)
`["10","20","30","40","15","7","49","2"]`

`(``)` apply the following tacit function to that:

the tally of elements
`8`

`⍵⍴⍨` use that to reshape the number of columns to be "transposed"
`[3,4,5,6,3,4,5,6]`

`,⍨` to that, append

the table-fied (made into single-column table) argument (the "transposed" columns)
`[[3,"10"],`
`[4,"20"],`
`[5,"30"],`
`[6,"40"],`
`[3,"15"],`
`[4,"7" ],`
`[5,"49"],`
`[6,"2" ]]`

`(``),` prepend the following:

`≢⍵` the tally of columns to be "transposed"
`4`

…`⌿⍨` use that to vertically replicate the rows of…

`t[;``]` all rows of the following columns of the table:

`⍉t` transpose the table
`[["0" ,"1" ],`
`["030915","030915"],`
`["10" ,"15" ],`
`["20" ,"7" ],`
`["30" ,"49" ],`
`["40" ,"2" ]]`

the tally of rows
`6`

**ɩ**ndices until that
`[1,2,3,4,5,6]`

`⍵~⍨` except the "transposed" column numbers
`[1,2]`

`[["0","030915"],`
`["1","030915"]]`

`[["0","030915"],`
`["0","030915"],`
`["0","030915"],`
`["0","030915"],`
`["1","030915"],`
`["1","030915"],`
`["1","030915"],`
`["1","030915"]]`

`[["0","030915",3,"10"],`
`["0","030915",4,"20"],`
`["0","030915",5,"30"],`
`["0","030915",6,"40"],`
`["1","030915",3,"15"],`
`["1","030915",4,"7" ],`
`["1","030915",5,"49"],`
`["1","030915",6,"2" ]]`

---
Tags: code-golf, array
---


title: Smallest web server

text:
# Question
Title: Smallest web server
**Create your smallest web server in your preferred language!**

Requirements

Must respond to atleast 1 type of request (get,post,patch,delete), with a specified string. Smallest implementation wins! \*String can be empty

You may use any library you want

My personal record for this was 56B in node

```
require('express')().use((r,w)=>w.send('')).listen(8080)

```

# Answer
# APL (Dyalog Unicode) with MiServer, 8 bytes

```
Start'.'

```

Starts a website on port 8080 serving the current directory.

This is what an interactive session transcript can look like:

```
      )xload miserver
.\miserver.dws saved Thu Apr  4 23:27:46 2019
      Start'.'
Virtual alias "PlugIns" overrides site path of same name.
MiServer for "." started on http://10.101.1.172:8080
Running in Debug mode (configured by setting <Production> in /Config/Server.xml)

```
> 2 votes

# Answer
# Python 3 with -m http.server, 11 bytes

No code. Just run python.

Try it online!
> 2 votes

---
Tags: code-golf
---


title: Two palindromes are not enough

text:
# Question
Title: Two palindromes are not enough
Some numbers, such as \\$14241\\$, are palindromes in base 10: if you write the digits in reverse order, you get the same number.

Some numbers are the sum of 2 palindromes; for example, \\$110=88+22\\$, or \\$2380=939+1441\\$.

For other numbers, 2 palindromes are not enough; for example, 21 cannot be written as the sum of 2 palindromes, and the best you can do is 3: \\$21=11+9+1\\$.

Write a function or program which takes integer input `n` and outputs the `n`th number which cannot be decomposed as the sum of 2 palindromes. This corresponds to OEIS A035137.

Single digits (including 0) are palindromes.

Standard rules for sequences apply:

* input/output is flexible
* you may use 0- or 1- indexing
* you may output the `n`th term, or the first `n` terms, or an infinite sequence

*(As a sidenote: all integers can be decomposed as the sum of at most 3 palindromes.)*

Test cases (1-indexed):

```
1 -> 21
2 -> 32
10 -> 1031
16 -> 1061
40 -> 1103

```

This is code-golf, so the shortest answer wins.

# Answer
# JavaScript (ES6),  ~~93 83 80~~  79 bytes

*Saved 1 byte thanks to @tsh*

Returns the \\$n\\$th term, 1-indexed.

```
i=>eval("for(n=k=1;k=(a=[...k+[n-k]+k])+''!=a.reverse()?k-1||--i&&++n:++n;);n")

```

Try it online!

### How?

Given \\$n\\$, we test whether there exists any \\$1\le k\le n\\$ such that both \\$k\\$ and \\$n-k\\$ are palindromes. If we do find such a \\$k\\$, then \\$n\\$ is the sum of two palindromes.

The trick here is to process \\$k\\$ and \\$n-k\\$ at the same time by testing a single string made of the concatenation of \\$k\\$, \\$n-k\\$ and \\$k\\$.

*Example:*

For \\$n=2380\\$:

* we eventually reach \\$k=1441\\$ and \\$n-k=939\\$
* we test the string "\\$1441\color{red}{939}1441\\$" and find out that it is a palindrome

### Commented

*NB: This is a version without `eval()` for readability.*

```
i => {                       // i = index of requested term (1-based)
  for(                       // for loop:
    n = k = 1;               //   start with n = k = 1
    k =                      //   update k:
      ( a =                  //     split and save in a[] ...
        [...k + [n - k] + k] //     ... the concatenation of k, n-k and k
      ) + ''                 //     coerce it back to a string
      != a.reverse() ?       //     if it's different from a[] reversed:
        k - 1                //       decrement k; if the result is zero:
          || --i             //         decrement i; if the result is not zero:
            && ++n           //           increment n (and update k to n)
                             //         (otherwise, exit the for loop)
      :                      //     else:
        ++n;                 //       increment n (and update k to n)
  );                         // end of for
  return n                   // n is the requested term; return it
}                            //

```
> 13 votes

# Answer
# Jelly,  ~~16 10~~  9 bytes

-1 byte thanks to Erik the Outgolfer. Outputs the first \\$n\\$ terms.

```
2_ŒḂƇ⁺ṆƲ#

```

Try it online!

I tried to come up with different idea compared to my original approach. Let's review the thinking process:

* Initially, the test worked as follows: It generated the integer partitions of that number, then filtered out those that also contained non-palindromes, then counted how many length-2 eligible lists there were. This was obviously not too efficient in terms of code length.
* Generating the integer partitions of \\$N\\$ and then filtering had 2 main disadvantages: length and time efficiency. To solve that issue, I thought I shall first come up with a method to generate *only* the pairs of integers \\$(x, y)\\$ that sum to \\$N\\$ (not all arbitrary-length lists) with the condition that both numbers must be palindrome.
* But still, I wasn't satisfied with the "classic way" of going about this. I switched approaches: instead of generating *pairs*, let's have the program focus on *idividual palindromes*. This way, one can simply compute all the palindromes \\$x\\$ below \\$N\\$, and if \\$N-x\\$ is also palindrome, then we're done.

### Code Explanation

```
2_ŒḂƇ⁺ṆƲ# – Monadic link or Full program. Argument: n.
2       # – Starting at 2<sup>*</sup>, find the first n integers that satisfy...
 _ŒḂƇ⁺ṆƲ  – ... the helper link. Breakdown (call the current integer N):
    Ƈ     – Filter. Creates the range [1 ... N] and only keeps those that...
  ŒḂ      – ... are palindromes. Example: 21 -> [1,2,3,4,5,6,7,8,9,11]
 _        – Subtract each of those palindromes from N. Example: 21 -> [20,19,...,12,10]
     ⁺    – Duplicate the previous link (think of it as if there were an additional ŒḂƇ
            instead of ⁺). This only keeps the palindromes in this list.
            If the list is non-empty, then that means we've found a pair (x, N-x) that
            contains two palindromes (and obviously x+N-x=N so they sum to N).
      Ṇ   – Logical NOT (we're looking for the integers for which this list is empty).
       Ʋ  – Group the last 4 links (basically make _ŒḂƇ⁺Ṇ act as a single monad).

```

* Any other non-zero digit works, for that matter.
> 12 votes

# Answer
# Jelly, 11 bytes

```
⁵ŻŒḂ€aṚ$EƲ#

```

Try it online!

The full program roughly works like this:

1. Set **z** to the input.
2. Set **x** to **10**.
3. Set **R** to **\[\]**.
4. For every integer **k** from **0** up to and including **x**, check whether both **k** and **x - k** are palindromic.
5. If all elements of **L** are equal (that is, if either all possible pairs that sum to **x** have both their elements palindromic, or all such pairs have at most one of their elements be palindromic), set **z** to **z - 1** and append **x** to **R**.
6. If **z = 0**, return **R** and end.
7. Set **x** to **x + 1**.
8. Go to step 4.

You may suspect that step 5 doesn't actually do the job it should. We should really not decrement **z** if all pairs that sum to **x** are palindromic. However, we can prove that this will never happen:

Let's first pick an integer \\$k\\$ so that \\$10\le k\le x\\$. We can always do so, because, at step 2, we initialize **x** to be **10**.

If \\$k\\$ isn't a palindrome, then we have the pair \\$(k,x-k)\\$, where \\$k+(x-k)=x\\$, therefore not all pairs have two palindromes.

If, on the other hand, \\$k\\$ is a palindrome, then we can prove that \\$k-1\\$ isn't a palindrome. Let the first and last digits of \\$k\\$ be \\$D\_F\\$ and \\$D\_L\\$ respectively. Since \\$k\\$ is a palindrome, \\$D\_F=D\_L\>0\\$. Let the first and last digits of \\$k-1\\$ be \\$D'\_F\\$ and \\$D'\_L\\$ respectively. Since \\$D\_L\>0\\$, \\$D'\_L=D'\_F-1\ne D'\_F\\$. Therefore, \\$k-1\\$ isn't a palindrome, and we have the pair \\$(k-1,x-(k-1))\\$, where \\$(k-1)+(x-(k-1))=k-1+x-k+1=x\\$.

We conclude that, if we start with setting **x** to a value greater than or equal to **10**, we can never have all pairs of non-negative integers that sum to **x** be pairs of palindromes.
> 7 votes

# Answer
## Haskell, ~~68~~ ~~67~~ 63 bytes

```
[n|n<-[1..],and[p a||p(n-a)|a<-[0..n]]]
p=((/=)=<<reverse).show

```

Returns an infinite sequence.

Collect all `n` where either `a` or `n-a` is not a palindrome for all `a <- [0..n]`.

Try it online!
> 3 votes

# Answer
# Retina, ~~135~~ 102 bytes

```
K`0
"$+"{0L$`\d+
*__
L$`
<$.'>$.`>
/<((.)*.?(?<-2>\2)*(?(2)$)>){2}/{0L$`\d+
*__
))L$`
<$.'>$.`>
0L`\d+

```

Try it online! Too slow for `n` of 10 or more. Explanation:

```
K`0

```

Start off by trying 0.

```
"$+"{

```

Repeat `n` times.

```
0L$`\d+
*__

```

Convert the current trial value to unary and increment it.

```
L$`
<$.'>$.`>

```

Create all pairs of non-negative integers that sum to the new trial value.

```
/<((.)*.?(?<-2>\2)*(?(2)$)>){2}/{

```

Repeat while there exists at least one pair containing two palindromic integers.

```
0L$`\d+
*__
))L$`
<$.'>$.`>

```

Increment and expand the trial value again.

```
0L`\d+

```

Extract the final value.
> 3 votes

# Answer
# Perl 5 `-MList::Util=any -p`, ~~59~~ 55 bytes

*-3 bytes thanks to @NahuelFouilleul*

```
++$\while(any{$\-reverse($\-$_)==reverse}0..$\)||--$_}{

```

Try it online!

Note: `any` could be replaced by `grep` and avoid the `-M` command line switch, but under the current scoring rules, that would cost one more byte.
> 3 votes

# Answer
# , ~~115~~ 111 bytes

*-4 thanks to Giuseppe*

```
function(n,r=0:(n*1e3))r[!r%in%outer(p<-r[Map(Reduce,c(x<-paste0),Map(rev,strsplit(a<-x(r),"")))==a],p,'+')][n]

```

Try it online!

Most of the work is packed into the function arguments to remove the `{}` for a multi-statement function call, and to reduce the brackets needed in defining the object `r`

Basic strategy is to find all palindromes up to a given bound (including 0), find all pairwise sums, and then take the n-th number not in that output.

The bound of `n*1000` was chosen purely from an educated guess, so I encourage anyone proving/disproving it as a valid choice.

`r=0:(n*1e3)`can probably be improved with a more efficient bound.

`Map(paste,Map(rev,strsplit(a,"")),collapse="")`is ripped from Mark's answer here, and is just incredibly clever to me.

`r[!r%in%outer(p,p,'+')][n]`reads a little inefficient to me.
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 124 bytes

```
n=>{int a=0;for(string m;n>0;)if(Enumerable.Range(0,++a).All(x=>!(m=x+""+(a-x)+x).Reverse().SequenceEqual(m)))n--;return a;}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~15~~ 12 bytes

```
°ÝDʒÂQ}ãOKIè

```

-3 bytes thanks to *@Grimy*.

0-indexed.
Very slow, so times out for most test cases.

Try it online or verify the first few cases by removing the.

**Much faster previous 15 byter version:**

```
µNÐLʒÂQ}-ʒÂQ}g_

```

1-indexed.

Try it online or output the first \\$n\\$ values.

**Explanation:**

```
°Ý              # Create a list in the range [0, 10**input]
  D             # Duplicate this list
   ʒÂQ}         # Filter it to only keep palindromes
       ã        # Take the cartesian product with itself to create all possible pairs
        O       # Sum each pair
         K      # Remove all of these sums from the list we duplicated
          Iè    # Index the input-integer into it
                # (after which the result is output implicitly)

µ               # Loop until the counter variable is equal to the (implicit) input-integer
 NÐ             #  Push the loop-index three times
   L            #  Create a list in the range [1, N] with the last copy
    ʒÂQ}        #  Filter it to only keep palindromes
        -       #  Subtract each from N
         ʒÂQ}   #  Filter it again by palindromes
             g_ #  Check if the list is empty
                #   (and if it's truthy: increase the counter variable by 1 implicitly)
                # (after the loop: output the loop-index we triplicated implicitly as result)

```
> 1 votes

# Answer
# , 57/60 bytes

```
0(](>:^:(1&e.p e.]-p=:(#~(-:|.)&":&>)&i.&>:)^:_)&>:)^:[~]

```

Try it online!

The linked version adds 3 bytes for a total of 60 in order to save as a function that the footer can call.

In the REPL, this is avoided by calling directly:

```
   0(](>:^:(1 e.q e.]-q=:(#~(-:|.)&":&>)&i.&>:)^:_)&>:)^:[~] 1 2 10 16 40
21 32 1031 1061 1103

```

## Explanation

The general structure is that of this technique from an answer by Miles:

```
(s(]f)^:[~]) n
          ]  Gets n
 s           The first value in the sequence
         ~   Commute the argument order, n is LHS and s is RHS
        [    Gets n
      ^:     Nest n times with an initial argument s
  (]f)         Compute f s
         Returns (f^n) s

```

This saved a few bytes over my original looping technique, but since the core function is my first attempt at writing J, there is likely still a lot that can be improved.

```
0(](>:^:(1&e.p e.]-p=:(#~(-:|.)&":&>)&i.&>:)^:_)&>:)^:[~]
0(]                                                 ^:[~] NB. Zero as the first term switches to one-indexing and saves a byte.
   (>:^:(1&e.p e.]-p=:(#~(-:|.)&":&>)&i.&>:)^:_)&>:)      NB. Monolithic step function.
                                                 >:       NB. Increment to skip current value.
   (>:^: <predicate>                        ^:_)          NB. Increment current value as long as predicate holds.
                   p=:(#~(-:|.)&":&>)&i.&>:               NB. Reused: get palindromes in range [0,current value].
                       #~(-:|.)&":&>                      NB. Coerce to strings keeping those that match their reverse.
                 ]-p                                      NB. Subtract all palindromes in range [0,current value] from current value.
    >:^:(1&e.p e.]-p                                      NB. Increment if at least one of these differences is itself a palindrome.

```
> 1 votes

# Answer
# Red, 142 bytes

```
func[n][i: 1 until[i: i + 1 r: on repeat k i[if all[(to""k)= reverse
to""k(s: to""i - k)= reverse copy s][r: off break]]if r[n: n - 1]n < 1]i]

```

Try it online!

Returns n-th term, 1-indexed
> 0 votes

# Answer
# Python 3, 107 bytes

```
p=lambda n:str(n)!=str(n)[::-1]
def f(n):
 m=1
 while n:m+=1;n-=all(p(k)+p(m-k)for k in range(m))
 return m

```

Try it online!

Inverting the palindrome checking saved 2 bytes :)

For reference the straight forward positive check (109 bytes):

```
p=lambda n:str(n)==str(n)[::-1]
def f(n):
 m=1
 while n:m+=1;n-=1-any(p(k)*p(m-k)for k in range(m))
 return m

```
> 0 votes

# Answer
# APL(NARS), 486 bytes

```
r←f w;p;i;c;P;m;j
p←{k≡⌽k←⍕⍵}⋄i←c←0⋄P←r←⍬
:while c<w
    i+←1
    :if   p i⋄P←P,i⋄:continue⋄:endif
    m←≢P⋄j←1
    :while j≤m
         :if 1=p i-j⊃P⋄:leave⋄:endif
         j+←1
    :endwhile
    :if j=m+1⋄c+←1⋄r←i⋄:endif
:endwhile

```

What is the word for break the loop? It seems it is ":leave", right? `{k≡⌽k←⍕⍵}` in p is the test for palindrome. This above function in the loop store all the palindrome found in the set P, if for some element w of P is such that i-w is in P too this means that the i is not right and we have increment i. Results:

```
  f 1
21
  f 2
32
  f 10
1031
  f 16
1061
  f 40
1103
  f 1000
4966
  f 1500
7536

```
> 0 votes

---
Tags: code-golf, sequence
---


title: n-level Ouroboros Quine

text:
# Question
Title: n-level Ouroboros Quine
This 128-language quine ouroboros (a program which outputs a program in another language, which outputs a program in yet another language, (125 languages later), which outputs the original program) is pretty impressive. But unfortunately, it has a static number of iterations.

Write a program which outputs a program (not necessarily in another language, but it can be), which outputs a program, which outputs a program, etc., which after n iterations, outputs the original program **for the first time** (i.e. no intermediate program should be the same as the original, because otherwise a quine which ignores its input would work), where n is a non-negative integer provided as input. The input can't be just a number in the original source code (e.g. putting `x = <the value of n>` at the start of your program), it should be one of the following:

1. Passed as a command-line argument
2. Read from standard input
3. Passed as an argument to a function, which returns/outputs the new program.

For intermediate stages in the ouroboros, your program can either be a fully-functioning program, or a function with no arguments, which, when called, will return/output the next one.

You may not read from the source file itself, or use any quine-like builtins (I don't think there are any which would do this, but there might be)

To be clear, if `n = 0`, the program should output its own source code.

If `n = 1`, the program should output a different program, which outputs the original source code.

And so on...

Fewest bytes wins!

**Edit:**

I should have written "For intermediate stages in the ouroboros, your program can either be a fully-functioning program **with no input**, or a function with no arguments". If your program outputs the next one in the chain, *then* waits for input, that's fine, but your program shouldn't need the original value of n.

# Answer
# 05AB1E, 28 bytes

*-4 bytes + fix thanks to Kevin Cruijssen*

```
"34çìD«s<©di®ì"34çìD«s<©di®ì

```

Try it online!

---

### Explanation

This works by appending the remaining number to print to the front of the code, which means it's added to the stack the same way an input would be. In the base case of input of "0" it will not concatenate the 0 on the front.
> 5 votes

# Answer
# Runic Enchantments, 39 bytes

```
"3X4+kSql1=c*?S:1-}C'LA-}!i:0)2*?~!'´@

```

Try it online!

Would be 4 bytes shorter than 05AB1E using the same tactic if inputs where less than or equal to `10`. But as we need to support arbitrarily large values, it gets more complicated.

Numerical value of `n` gets placed at the front and parsed as a continuous number literal using `´`. `"3X4+kSq` is the basic quine code. If no value is present at the front, the stack length will only be 1 (the quine) otherwise 2 letting `l1=d*?` determine how to handle things from there.

* If there is a value, `S:1-}'LA2+-}` runs: swap the value to the top, subtract 1, duplicate it, leaving a copy on the bottom of the stack, get the Log10 of that value times 100 (resulting in the value's own character length, plus 1 for the `´`), remove that many characters from the end of the string (effectively truncating itself off the end, both *where* it isn't needed *and* because it has the wrong value). `C` is one byte shorter than `2+` and results in the same value.
* If there is not a value, read one from input.

Regardless: `:0)2*?` duplicate and compare with zero.

* If non-zero push `´`.
* If zero, pop the value. We can cheat using `!` instead of `2?` and save a byte because when `´` tries to execute the first byte it sees is non-numeric and immediately drops out of number mode at the same position.

Print entire stack top to bottom.
> 4 votes

# Answer
# Java 10, 145 bytes

```
n->{Long N=n;var s="n->{Long N=%s;var s=%c%s%2$c;return s.format(s,N>0?N-1+%2$cL%2$c:%2$cn%2$c,34,s);}";return s.format(s,N>0?N-1+"L":"n",34,s);}

```

Try it online and see the outputs of some iterations.

**Explanation:**

**explanation:**

* The `var s` contains the unformatted source code
* `%s` is used to put this String into itself with `s.format(...)`
* `%c`, `%1$c`, and `34` are used to format the double-quotes
* `s.format(s,34,s)` puts it all together

**Challenge part:**

The first lambda function takes a `long` input as parameter.

* This is set in variable `Long N=n;` in the first iteration. Or in `Long N=%s;` for next iterations.
* The ternary check `N>0?N-1+"L":"n"` will fill this `%s` with value `N-1`, appended with `L` since it's a long and to convert it to a String for the `%s`, if `N` is larger than 1. If `N` is 0 instead (initial input was `0` or this is the last iteration of the interquine-'loop'), it will fill this `%s` with the initial `n` instead.
> 3 votes

# Answer
# Python 3.8 (pre-release), ~~60~~ ~~56~~ ~~55~~ 53 bytes

```
lambda n=-1,s='lambda n=%d,s=%r:s%%(~-n,s)':s%(~-n,s)

```

Try it online!

*-2 bytes thanks to Jo King*

As of the 53 byte version, also works in Python 2 and Python 3.
> 2 votes

# Answer
# Jelly, ~~22~~ 20 bytes

```
“Ṫ_1xẸƲ;Ṿ⁾v,⁾¥ ”v,¥

```

Try it online!

Try repeated calls of code

A full program that takes a single argument \\$n\\$. Main version outputs correctly to stdout but cannot be used as a function with a function return. The repeated calls version is 2 bytes longer but returns programmatically usable output. L
> 2 votes

# Answer
# Haskell, ~~195~~ 164 bytes

```
main=putStr(x++show x++"\na=")>>(getLine:cycle[pure$show$a-1])!!a>>=putStr
x="main=putStr(x++show x++\"\\na=\")>>(getLine:cycle[pure$show$a-1])!!a>>=putStr\nx="
a=0

```

Try it online!

This uses a pretty simple quine technique. We modify it with a variable `a` which is set to a number. If that number is zero (which it is at the start) we take input and output our source with `a` set to the input number. If `a` is not zero we output our source with `a` set to one less. This way `a` counts down to zero before outputting the original source.
> 2 votes

# Answer
# , 92 bytes

```
f=function(n=-1){gsub("\\s","",paste("f=",sub("-?\\d+",n-1,paste(deparse(f),collapse=""))))}

```

Try it online!

If `deparse` is deemed cheating, here’s an alternative:

# , 108 bytes

```
function(n=-1){s="function(n=%d){s=%s%s%2$s;sprintf(s,n-1,intToUtf8(34),s)}";sprintf(s,n-1,intToUtf8(34),s)}

```

Try it online!
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 112 bytes

```
void f(int n=-1){var s="void f(int n={2}){{var s={0}{1}{0};Write(s,(char)34,s,n-1);}}";Write(s,(char)34,s,n-1);}

```

Saved a lot of bytes thanks to @NickKennedy!

Try it online!
> 1 votes

# Answer
# Perl 6, 44 bytes

```
<say '<',S{\d+}=get||0-1,'>~~.EVAL'>~~.EVAL

```

Try it online!

Takes input via standard input and returns a program where the only thing changed is the first number. Each subsequent program will then output the same program, except with that number decremented.
> 1 votes

---
Tags: code-golf, quine
---


title: Sum of Products of Subsets

text:
# Question
Title: Sum of Products of Subsets
Given an integer k and a list of integers A of size n, find the product of all subsets in A of size k and sum them together.

For example,

```
k = 2
n = 4
A = 1 2 3 4

```

The subsets of size 2 and their products are

```
1 2 = 2
1 3 = 3
1 4 = 4
2 3 = 6
2 4 = 8
3 4 = 12

```

which sum together to 35.

Some test cases:

## Input

```
A = 73 36 86 76 5 25 15 95 27 1
n = 10
k = 4

A = 7 16 56 83 14 97 71 24 65 32 75 61 64 73 94 34 10
n = 17
k = 3

```

## Output

```
499369377

87409828

```

The input can be in whatever format suits your language best. You can have, for example, the variables A, n, and k set to the input already. The integers in A are not necessarily unique.

## Constraints

Functions which solve this question are not allowed, as well as functions which generate subsets. Also, to avoid Θ(n^k) submissions, if a solution is made using a better approach, it will have a -30 character bonus. (-30 is subject to change)

The shortest solution is the winner.

Side Note: It's okay to post solutions which do not follow the rules if it demonstrates the strengths of your language. It just won't be part of the scoring.

For example,

Mathematica (31)

```
Times@@#&/@A~Subsets~{k}//Total

```

# Answer
> 1 votes
### GolfScript, score 8 0 -3 (27 - 30)

```
1,*1+\{{*\(@+}+1$1>0+%+}/0=

```

Expects list `a` and `k` on the stack and returns the result.

Example (run online):

```
[73 36 86 76 5 25 15 95 27 1] 4
1,*1+\{{*\(@+}+1$1>0+%+}/0=
# 499369377

```

# Answer
> 5 votes
## R - 20

Since the OP said:

*Side Note: It's okay to post solutions which do not follow the rules if it demonstrates the strengths of your language. It just won't be part of the scoring.*

```
sum(combn(A,k,prod))

```

# Answer
> 2 votes
### Ruby, O(n\*k), 70 - 30 = 40 characters

```
@r={};r=->a,n,k{@r[[a,n,k]]||=k<1?1:n<1?0:r[a,n-=1,k]+a[n]*r[a,n,k-1]}

```

if the array can be made global and constant (or if we can ask the caller to clean our cache), we can save seven (or thirteen) more characters.

```
r=->n,k{@r[[n,k]]||=k<1?1:n<1?0:r[n-=1,k]+@a[n]*r[n,k-1]}

```

without memoisation, we're at 50 characters, but we don't qualify for the bonus:

```
r->a,n,k{k<1?1:n<1?0:r[a,n-=1,k]+a[n]*r[a,n,k-1]}

```

Spaced apart:

```
r = -> a, n, k {
  k<1 ? 1 :
  n<1 ? 0 :
  r[a, n-1, k] + a[n-1] * r[a, n-1, k-1]
}

```

With memoization, we get to O(n * k * cost\_of\_memoization). If the key cannot be hashed well, the cost of memoization quickly grows up. However, a key of the form \[\[?\],#,#\] can be hashed quite well, at least in theory. Let's also assume that Ruby arrays cache their hashes, so hashing the same array over and over again takes the same time as hashing it once - linear in size. Also, hash table lookup may be assumed constant-time. So, it is safe to assume that the cost of memoization is constant per lookup, and the initial cost for hashing the array is drowned in the rest of the lookup.

here is the iterative approach:

```
r={};0.upto(k){|k|0.upto(n){|n|r[[n,k]]=k<1?1:n<1?0:r[[n-=1,k]]+a[n]*r[[n,k-1]]}};r[[n,k]]

```

Yay! I've beaten Daniero's cheating solution

# Answer
> 1 votes
## APL (31)

This assumes that `A`, `k` and `n` are already set.

```
+/{×/A[⍵]}¨({∧/2</⍵}¨∆)/∆←,⍳k⍴n

```

I.e.:

```
      A ← 73 36 86 76 5 25 15 95 27 1
      n ← 10
      k ← 4
      +/{×/A[⍵]}¨({∧/2</⍵}¨∆)/∆←,⍳k⍴n
499369377

```

Explanation:

* `∆←,⍳k⍴n`: set  to the flattened (`,`) coordinate vector () which is `k`-dimensional with size `n` in each dimension. I.e. if `k=2` and `n=3`, you get `(1 1) (1 2) (1 3) (2 1) (2 2) (2 3) (3 1) (3 2) (3 3)`.
* `({∧/2</⍵}¨∆)/`: select only those coordinates where the value for the *N*-th dimension is larger than the value for the *(N-1)*-th dimension. (I.e. you get `(1 2) (1 3) (2 3)`). When these sets of coordinates are interpreted as lists of indexes into `A`, we get the desired subsets.
* `{×/A[⍵]}¨`: for each subset, get the values from `A` and multiply them together.
* `+/`: sum the given values

# Answer
> 1 votes
## Python 2: 64-30=34

```
t=A
exec"t=[sum(t[:i])*A[i]for i in range(n)];"*~-k
print sum(t)

```

Input is expected as

```
A = [73, 36, 86, 76, 5, 25, 15, 95, 27, 1]
n = 10
k = 4

```

Then `499369377` gets printed.

# Answer
> 1 votes
# Jelly, 5 bytes

```
œcP€S

```

Try it online!

Expects \\$A\\$ and \\$k\\$ as input.

**Explanation:**

```
œcP€S
œc        Combinations
  P€      Product of €ach
    S     Sum

```

# Answer
> 0 votes
I'm feeling too lazy to create the subsets on my own, so here's a quick cheating solution.

# Ruby, 48 chars

```
A.combination(k).map{|x|x.inject :*}.inject :+

```

With A and k are predefined, like for instance so

```
A=[7,16,56,83,14,97,71,24,65,32,75,61,64,73,94,34,10]
k=3

```

the result is `87409828`.

# Answer
> 0 votes
## Python 2, 172-30=142

Similar buildup approach

```
r=range
m=[x[:]for x in[[0]*n]*k]
m[0][0]=A[0]
for i in r(1,n):m[0][i]=m[0][i-1]+A[i]
for j in r(1,n):
 for i in r(1,k):m[i][j]=m[i][j-1]+m[i-1][j-1]*A[j]
print m[k-1][n-1]

```

# Answer
> 0 votes
# J, 35 bytes

```
[:+/(>@{[:(</.~+/"1)2#:@i.@^#)*/@#]

```

Generates the masks for the powerset of *A* in binary order, selects the masks for *k*, and operates on each subset.

## Usage

```
   f =: [:+/(>@{[:(</.~+/"1)2#:@i.@^#)*/@#]
   2 f 1 2 3 4
35
   4 f 73 36 86 76 5 25 15 95 27 1
499369377
   3 f 7 16 56 83 14 97 71 24 65 32 75 61 64 73 94 34 10
87409828

```

## Explanation

```
[:+/(>@{[:(</.~+/"1)2#:@i.@^#)*/@#]  Input: k on LHS, A on RHS
                            #        Get the size of A
                    2      ^         Get 2^len(A)
                        i.@          Get the range [0, 1, ..., 2^len(A)-1]
                     #:@             Convert each to binary
        [:     +/"1                  Take the sum of each binary digits
           </.~                      Partition the list of binary digits by their sum
                                     and box each group
       {                             Select the box at index k
     >@                              Unbox it to get the mask for subsets of size k
                                  ]  Get A
                                 #   Copy from A using each mask
                              */@    For each subset, reduce using multiplication
[:+/                                 Reduce the products using addition and return

```

# Answer
> 0 votes
# APL(NARS), 47 chars, 98 bytes

```
{+/×/¨{w[⍵]}¨k/⍨{∧/</¨¯1↓{⍵,¨1⌽⍵}⍵}¨k←,⍳⍺⍴≢w←⍵}

```

I got the idea from "marinus" answer, i don't know if this is ok... test:

```
  f←{+/×/¨{w[⍵]}¨k/⍨{∧/</¨¯1↓{⍵,¨1⌽⍵}⍵}¨k←,⍳⍺⍴≢w←⍵}
  2 f 1 2 3 4
35
  3 f 7 16 56 83 14 97 71 24 65 32 75 61 64 73 94 34 10
87409828
  4 f 73 36 86 76 5 25 15 95 27 1
499369377

```

`{∧/</¨¯1↓{⍵,¨1⌽⍵}⍵}` find if index are all \< each other for example

```
  {∧/</¨¯1↓{⍵,¨1⌽⍵}⍵} 1 2 3 4 5
1
  {∧/</¨¯1↓{⍵,¨1⌽⍵}⍵} 3 2 3 4 5
0
  {∧/</¨¯1↓{⍵,¨1⌽⍵}⍵} 1 3 2 4 5
0
  {∧/</¨¯1↓{⍵,¨1⌽⍵}⍵} 1 2 3 4 9
1

```

I would prefer this because this work on indices not on values...possible if some repetitions, for list has one meaning...

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 167 bytes

```
l=>l.Any()?A(l.Skip(1)).Select(x=>l.Take(1).Union(x)).Union(A(l.Skip(1))):new int[][]{new int[]{}};B=(n,l)=>A(l).Where(x=>x.Count()==n).Sum(x=>x.Aggregate((y,z)=>y*z))

```

Try it online!

```
//returns a list of all the subsets of a list
A=l=>l.Any()?A(l.Skip(1)).Select(x=>l.Take(1).Union(x)).Union(A(l.Skip(1))):new int[][]{new int[]{}};

//filter the subsets of the required size and return the sum of the products of their items
B=(n,l)=>A(l).Where(x=>x.Count()==n).Sum(x=>x.Aggregate((y,z)=>y*z))

```

---
Tags: code-golf, set-theory
---


# Question
Title: List the combinations of elements in a set
Given a set of `n` elements, the challenge is to write a function who lists all the combinations of `k` elements of in this set.

## Example

```
Set: [1, 7, 4]
Input: 2
Output: [1,7], [1,4], [7,4]

```

## Example

```
Set: ["Charlie", "Alice", "Daniel", "Bob"]
Input: 2
Output ["Daniel", "Bob"], ["Charlie", "Alice"], ["Alice", "Daniel"], ["Charlie", "Daniel"], ["Alice", "Bob"], ["Charlie",  "Bob"]

```

## Rules (Edited)

* The order of the output is of your choice.
* The input may be any type of data. But the output should be the same type as the input. If the input is a list of integers, the output should be a list of integers as well. If the input is a string (array of characters), the output should be a string as well.
* The code should work with any number of input variables.
* You can use any programming language.
* The answer should be able to use anything (string, int, double...) as input and output as well.
* Any built-in functions that is related to combinations and permutations are forbidden.
* Shortest code wins (in terms of bytes).
* Tiebreaker: votes.
* Duration: 1 week.

P.S. Be careful about the *extreme* inputs such as negative numbers, 0, etc.

# Answer
> 13 votes
# Haskell - 57 46 bytes

Bring it on, golfscripters.

```
0%_=[[]]
n%(x:y)=map(x:)((n-1)%y)++n%y
_%_=[]

```

Use case (same function works polymorphicaly):

> 2%\[1,2,3,4\] ➔ \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\]
>
> 3%"cheat" ➔ \["che","cha","cht","cea","cet","cat","hea","het","hat","eat"\]
>
> 2%\["Charlie", "Alice", "Daniel", "Bob"\] ➔ \[\["Charlie","Alice"\],\["Charlie","Daniel"\],\["Charlie","Bob"\],\["Alice","Daniel"\],\["Alice","Bob"\],\["Daniel","Bob"\]\]

# Answer
> 7 votes
# Python (72)

```
f=lambda S,k:S and[T+S[:1]for T in f(S[1:],k-1)]+f(S[1:],k)or[[]]*(k==0)

```

The function `f` takes a list `S` and number `k` and returns a list of all sublists of length `k` of `S`. Rather than listing all subsets and then filtering by size, I only get the subsets of the needed size at each step.

I'd like to get `S.pop()` to work in order to combine getting `S[:1]` with passing `S[1:]` later, but it seems to consume the list too much.

To preempt the objection any such Python solution breaks the rule that "The code should work in any number of input variables" because of recursion limits, I'll note that the Stackless Python implementation has no recursion limits (though I haven't actually tested this code with it).

Demonstration:

```
S = [1, 2, 6, 8]
for i in range(-1,6):print(i, f(S,i))

#Output:
-1 []
0 [[]]
1 [[1], [2], [6], [8]]
2 [[2, 1], [6, 1], [8, 1], [6, 2], [8, 2], [8, 6]]
3 [[6, 2, 1], [8, 2, 1], [8, 6, 1], [8, 6, 2]]
4 [[8, 6, 2, 1]]
5 []

```

# Answer
> 3 votes
# Mathematica 10, 70 chars

Just a translation of the Haskell answer.

```
_~f~_={};_~f~0={{}};{x_,y___}~f~n_:=Join[Append@x/@f[{y},n-1],{y}~f~n]

```

Usage:

> In\[1\]:= f\[{1, 7, 4}, 2\]
>
> Out\[1\]= {{7, 1}, {4, 1}, {4, 7}}

# Answer
> 3 votes
# Haskell + Data.List, 44 bytes

```
0%_=[[]]
n%y=do{a:b<-tails y;(a:)<$>(n-1)%b}

```

Try it online!

---

The 46 byte answer is pretty hard to beat but if you have `tails` from `Data.List` you can do 44 bytes.

# Answer
> 3 votes
# Charcoal, 23 bytes

```
ＥΦＥＸ²Ｌθ⮌↨ι²⁼ΣιηΦ…θＬι§ιμ

```

Try it online! Link is to verbose version of code. Explanation:

```
    ²                   Literal 2
   Ｘ                    Raised to power
     Ｌ                  Length of
      θ                 Input array
  Ｅ                     Mapped over implicit range
         ι              Current index
        ↨               Converted to base
          ²             Literal 2
       ⮌                Reversed
 Φ                      Filtered on
            Σ           Digital sum of
             ι          Current base 2 value
           ⁼            Equal to
              η         Input `k`
Ｅ                       Mapped to
                 θ      Input array
                …       Chopped to length
                  Ｌ     Length of
                   ι    Current base 2 value
               Φ        Filtered on
                     ι  Current base 2 value
                    §   Indexed by
                      μ Current index

```

# Answer
> 2 votes
# Python - 129

s is a list, k is the size of the combinations to produce.

```
def c(s, k):
    if k < 0: return []
    if len(s) == k: return [s]
    return list(map(lambda x: [s[0]]+x, c(s[1:], k-1))) + c(s[1:], k)

```

# Answer
> 2 votes
# Python, 102

```
p=lambda s:p(s[1:])+[x+[s[0]]for x in p(s[1:])]if s else[s];c=lambda s,k:[x for x in p(s)if len(x)==k]

```

Call c to run:

> c(\[5, 6, 7\], 2) =\> \[\[6, 7\], \[5, 7\], \[5, 6\]\]

It gets all the permutations of the list s and filters the ones with length k.

# Answer
> 2 votes
# Pyth, 28

```
DcGHR?+m+]'HdctGtHcGtHH*]Y!G

```

This is (heavily) based on the Haskell answer.

Explanation:

```
DcGH                           def c(G,H):
    R                          return
     ?                         Python's short circuiting _ if _ else _
       m+]'Hd                  map to [head(H)]+d
             ctGtH             c(G-1,tail(H))
       m+]'HdctGtH             map [head(H)]+d for d in c(tail(G),tail(H))
      +m+]'HdctGtHcGtH         (the above) + c(G,tail(H))
     ?                H        (the above) if H else (the below)
                       *]Y!G   [[]]*(not G)

```

Note: While the most recent version of Pyth, 1.0.9, was released tonight, and is therefore ineligible for this challenge, the same code works fine in 1.0.8.

# Answer
> 2 votes
# APL(NARS), 80 chars, 160 bytes

```
{h←{0=k←⍺-1:,¨⍵⋄(k<0)∨k≥i←≢w←⍵:⍬⋄↑,/{w[⍵],¨k h w[(⍳i)∼⍳⍵]}¨⍳i-k}⋄1≥≡⍵:⍺h⍵⋄⍺h⊂¨⍵}

```

test and how to use it:

```
  f←{h←{0=k←⍺-1:,¨⍵⋄(k<0)∨k≥i←≢w←⍵:⍬⋄↑,/{w[⍵],¨k h w[(⍳i)∼⍳⍵]}¨⍳i-k}⋄1≥≡⍵:⍺h⍵⋄⍺h⊂¨⍵}
  o←⎕fmt
  o 5 f 1 2 3 4
┌0─┐
│ 0│
└~─┘
  o 4 f 1 2 3 4
┌1─────────┐
│┌4───────┐│
││ 1 2 3 4││
│└~───────┘2
└∊─────────┘
  o 3 f 1 2 3 4
┌4──────────────────────────────────┐
│┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐│
││ 1 2 3│ │ 1 2 4│ │ 1 3 4│ │ 2 3 4││
│└~─────┘ └~─────┘ └~─────┘ └~─────┘2
└∊──────────────────────────────────┘
  o 2 f 1 2 3 4
┌6────────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐│
││ 1 2│ │ 1 3│ │ 1 4│ │ 2 3│ │ 2 4│ │ 3 4││
│└~───┘ └~───┘ └~───┘ └~───┘ └~───┘ └~───┘2
└∊────────────────────────────────────────┘
  o 1 f 1 2 3 4
┌4──────────────────┐
│┌1─┐ ┌1─┐ ┌1─┐ ┌1─┐│
││ 1│ │ 2│ │ 3│ │ 4││
│└~─┘ └~─┘ └~─┘ └~─┘2
└∊──────────────────┘
  o 0 f 1 2 3 4
┌0─┐
│ 0│
└~─┘
  o ¯1 f 1 2 3 4
┌0─┐
│ 0│
└~─┘
  o 3 f (0 0)(1 2)(3 ¯4)(4 ¯5)
┌4────────────────────────────────────────────────────────────────────────────────────────────────┐
│┌3────────────────────┐ ┌3────────────────────┐ ┌3─────────────────────┐ ┌3─────────────────────┐│
││┌2───┐ ┌2───┐ ┌2────┐│ │┌2───┐ ┌2───┐ ┌2────┐│ │┌2───┐ ┌2────┐ ┌2────┐│ │┌2───┐ ┌2────┐ ┌2────┐││
│││ 0 0│ │ 1 2│ │ 3 ¯4││ ││ 0 0│ │ 1 2│ │ 4 ¯5││ ││ 0 0│ │ 3 ¯4│ │ 4 ¯5││ ││ 1 2│ │ 3 ¯4│ │ 4 ¯5│││
││└~───┘ └~───┘ └~────┘2 │└~───┘ └~───┘ └~────┘2 │└~───┘ └~────┘ └~────┘2 │└~───┘ └~────┘ └~────┘2│
│└∊────────────────────┘ └∊────────────────────┘ └∊─────────────────────┘ └∊─────────────────────┘3
└∊────────────────────────────────────────────────────────────────────────────────────────────────┘
  o 4 f (0 0)(1 2)(3 ¯4)(4 ¯5)
┌1──────────────────────────────┐
│┌4────────────────────────────┐│
││┌2───┐ ┌2───┐ ┌2────┐ ┌2────┐││
│││ 0 0│ │ 1 2│ │ 3 ¯4│ │ 4 ¯5│││
││└~───┘ └~───┘ └~────┘ └~────┘2│
│└∊────────────────────────────┘3
└∊──────────────────────────────┘
  o 1 f (0 0)(1 2)(3 ¯4)(4 ¯5)
┌4────────────────────────────────────┐
│┌1─────┐ ┌1─────┐ ┌1──────┐ ┌1──────┐│
││┌2───┐│ │┌2───┐│ │┌2────┐│ │┌2────┐││
│││ 0 0││ ││ 1 2││ ││ 3 ¯4││ ││ 4 ¯5│││
││└~───┘2 │└~───┘2 │└~────┘2 │└~────┘2│
│└∊─────┘ └∊─────┘ └∊──────┘ └∊──────┘3
└∊────────────────────────────────────┘
  o 2 f ('Charli')('Alice')('Daniel')('Bob')
┌6──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│┌2─────────────────┐ ┌2──────────────────┐ ┌2───────────────┐ ┌2─────────────────┐ ┌2──────────────┐ ┌2───────────────┐│
││┌6──────┐ ┌5─────┐│ │┌6──────┐ ┌6──────┐│ │┌6──────┐ ┌3───┐│ │┌5─────┐ ┌6──────┐│ │┌5─────┐ ┌3───┐│ │┌6──────┐ ┌3───┐││
│││ Charli│ │ Alice││ ││ Charli│ │ Daniel││ ││ Charli│ │ Bob││ ││ Alice│ │ Daniel││ ││ Alice│ │ Bob││ ││ Daniel│ │ Bob│││
││└───────┘ └──────┘2 │└───────┘ └───────┘2 │└───────┘ └────┘2 │└──────┘ └───────┘2 │└──────┘ └────┘2 │└───────┘ └────┘2│
│└∊─────────────────┘ └∊──────────────────┘ └∊───────────────┘ └∊─────────────────┘ └∊──────────────┘ └∊───────────────┘3
└∊──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
  o ¯2 f ('Charli')('Alice')('Daniel')('Bob')
┌0─┐
│ 0│
└~─┘

```

the output seems ok... but bug are possible...

In practice it return void set as Zilde if input alpha out of range; if alpha is 1 it return the elements all one in its set (is it right?);

This below it seems a couple of char less but 2x slower above:

```
f←{(⍺>≢⍵)∨⍺≤0:⍬⋄1=⍺:,¨⍵⋄{w[⍵]}¨k/⍨{∧/</¨¯1↓{⍵,¨1⌽⍵}⍵}¨k←,⍳⍺⍴≢w←⍵}

```

# Answer
> 2 votes
# 05AB1E, ~~14~~ 13 bytes

```
goLε¹ybRÏ}ʒgQ

```

Inspired by *@Neil*'s Charcoal answer, so make sure to upvote him!

Try it online or verify a few more test cases.

If builtins were allowed this could have been 2 bytes:

Try it online or verify a few more test cases.

**Explanation:**

```
g              # Get the length of the first (implicit) input-list
 o             # Take 2 to the power this length
  L            # Create a list in the range [1, 2**length]
   ε           # Map each integer `y` to:
    ¹          #  Push the first input-list again
     ybR       #  Convert integer `y` to binary, and reverse it
        Ï      #  And only keep values at truthy indices of `y` (so where the bit is a 1)
         }ʒ    # After the map: filter the list of lists by:
           g   #  Where the length of the inner list
            Q  #  Is equal to the (implicit) input-integer
               # (then the result is output implicitly)

.Æ             # Get all `b`-element combinations in list `a`,
               # where `b` is the first (implicit) input-integer,
               # and `a` is the second (implicit) input-list
               # (then the result is output implicitly)

```

# Answer
> 1 votes
# JS - 117 188

```
(a,b,c=[])=>((d=(e,f,g=[])=>f*e?g.push(e)+d(e-1,f-1,g)+g.pop
()+d(e-1,f,g):f||c.push(g.map(b=>a[b-1])))(a.length,b),c)

```

> (\<source code\>)(\['Bob','Sally','Jonah'\], 2)
>
> \[\['Jonah','Sally'\]\['Jonah','Bob'\]\['Sally','Bob'\]\]

**Array method madness**

```
combination = (arr, k) =>
    Array
        .apply(0, { length: Math.pow(k+1, arr.length) })
        .map(Number.call, Number)
        .map(a => a
              .toString(arr.length)
              .split('')
              .sort()
              .filter((a, b, c) => c.indexOf(a) == b)
              .join(''))
        .filter((a, b, c) => a.length == k && c.indexOf(a) == b)
        .map(x => x.split('').map(y => arr[+y]))

```

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 141 bytes

```
l=>l.Any()?A(l.Skip(1)).Select(x=>l.Take(1).Union(x)).Union(A(l.Skip(1))):new object[][]{new object[]{}};B=(n,l)=>A(l).Where(x=>x.Count()==n)

```

Sadly, Tio/Mono doesn't seem to support generic type **T** declaration, so I'm forced to lose a few bytes with the **object** type instead.

```
//returns a list of all the subsets of a list
A=l=>l.Any()?A(l.Skip(1)).Select(x=>l.Take(1).Union(x)).Union(A(l.Skip(1))):new object[][]{new object[]{}};

//return the subsets of the required size
B=(n,l)=>A(l).Where(x=>x.Count()==n);

```

Try it online!

---
Tags: code-golf
---