title: CSS Color Golf!

text:
# Question
Title: CSS Color Golf!
You are a web developer, and your boss has decided to update the company's website. He has decided that less color is better, but he wants the site to look the same. You justly decide that he has no idea what he's talking about, but you're going to try anyway, because you're bored. Since the company has thousands of webpages, and each one has its own CSS, you decide to write a script to do the necessary changes. Parsing HTML not required.

All of the pages currently use a string like `rgb(255,0,0)` for a color. **Given the three decimal values** representing the RGB values of a CSS color attribute (in that order), return or print the shortest string representation of that color, such that it's usable for CSS like so: `color:<your-result-here>;`.

Here is a complete table of valid **CSS Color Keywords**. They are case-insensitive.

### Examples:

Note that colors can be defined with 12 or 24 bits. The pattern `#ABC` is a shorter version of `#AABBCC`. Chuck Norris is a color.

Your program will only take in 3 integers, not a string (with the exception of the *"bonus"* mentioned later).

```
0, 0, 0         ->  #000        (same as #000000, but shorter)
255, 0, 0       ->  red
0, 128, 128     ->  TEAL
139, 0, 0       ->  DarkRed     (OR #8B0000)
72, 61, 139     ->  #483D8B
255, 255, 254   ->  #fffffe
255, 85, 255    ->  #f5f        (same as #ff55ff, but shorter)

```

### Scoring / Rules

* Shortest code wins!
* Standard loopholes are disallowed, with the exception of built-ins.
* **-50% bytes** (the bonus is rounded down) if you accept *any\** valid color selector and output the shortest. So `DarkSlateBlue` would output `#483D8B`, `#F00` outputs `red`, etc.
    + \*This only includes RGB, hex codes, and names.
    + Note that some colors have alternate names due to X11 (like `Fuchsia` and `Magenta`, or `Cyan` and `Aqua`). The alternate names are included in the linked list of CSS Color Keywords according to the W3 standard.
* CSS3 is Turing Complete. That'd be worth a bounty.

Edit:

* **PLEASE RUN YOUR CODE ON THE TEST CASES!**

# Answer
> 5 votes
# Perl, 212 - 50% = 106 bytes

```
use aliased Graphics::ColorNames,G;sub c{tie%c,G,CSS;$_=pop;$c={reverse%c}->{$_=sprintf'%02x'x(@0=/(\d+, ?)((?1))(\d+)/)||$c{s/#(.)(.)(.)$|#/\1\1\2\2\3\3/r},@0};s/(.)\1(.)\2(.)\3|/#\1\2\3/;y///c>length$c&&$c||$_}

```

With newlines added:

```
use aliased Graphics::ColorNames,G;
sub c{
  tie%c,G,CSS;$_=pop;
  $c={reverse%c}->{
    $_=sprintf'%02x'x(@0=/(\d+, ?)((?1))(\d+)/)||$c{s/#(.)(.)(.)$|#/\1\1\2\2\3\3/r},@0
  };
  s/(.)\1(.)\2(.)\3|/#\1\2\3/;
  y///c>length$c&&$c||$_
}

```

---

**Test Cases**

```
use feature say;

say c '#f00';
say c '#FF0000';
say c '#112233';
say c '#f0ffff';
say c 'azure';
say c 'DARKSLATEBLUE';
say c 'rgb(255, 127, 80)';
say c 'rgb(255, 255, 254)';
say c 'rgb(255,228,196)';

```

**Output**

```
red
red
#123
azure
azure
#483d8b
coral
#fffffe
bisque

```

---

# Perl, no bonus, 144 bytes

```
use aliased Graphics::ColorNames,G;sub c{tie%c,G,CSS;$c={reverse%c}->{$_=sprintf'%02x'x3,@_};s/(.)\1(.)\2(.)\3|/#\1\2\3/;y///c>length$c&&$c||$_}

```

With newlines added:

```
use aliased Graphics::ColorNames,G;
sub c{
  tie%c,G,CSS;
  $c={reverse%c}->{
    $_=sprintf'%02x'x3,@_
  };
  s/(.)\1(.)\2(.)\3|/#\1\2\3/;
  y///c>length$c&&$c||$_
}

```

`Graphics::ColorNames` isn't a core module, but it's been around since 2001. You may need to install it via:

```
cpan install Graphics::ColorNames
cpan install Graphics::ColorNames::CSS

```

The hex representation is preferred if the color name has the same length.

---

**Test Cases**

```
use feature say;

say c 0, 0, 0;
say c 255, 0, 0;
say c 0, 128, 128;
say c 139, 0, 0;
say c 72, 61, 139;
say c 255, 255, 254;
say c 255, 85, 255;

```

**Output**

```
#000
red
teal
#8b0000
#483d8b
#fffffe
#f5f

```

# Answer
> 10 votes
# C#6 527 bytes / 2 bonus = 264

**EDIT:** Woot! I finally got the bonus answer with a lower score than the basic answer!

I've written just a function. It requires a `using` statement (included.)

C# has a nice list of known colours to work with, but it insists on including the Alpha channel. The known colours also includes all system colours, two of which have names less than 7 characters long, so these needed to be stripped out.

Here's the bonus solution, supporting formats such as:

* `12, 34, 56`
* `#123`
* `#123456`
* `DarkSlateBlue`

Completely golfed:

```
using System.Drawing;int H(string s,int i,int l)=>Convert.ToInt32(s.Substring(i*l+1,l),16)*(l<2?17:1);string D(string a){int i=17,j=a.Length/3,n;var d=a.Split(',');Color k,c=a[0]<36?Color.FromArgb(H(a,0,j),H(a,1,j),H(a,2,j)):Color.FromName(a);c=c.A>0?c:Color.FromArgb(int.Parse(d[0]),int.Parse(d[1]),int.Parse(d[2]));j=c.R%i+c.G%i+c.B%i<1?3:6;n=c.ToArgb();a="#"+(j<6?c.R/i<<8|c.G/i<<4|c.B/i:n&0xffffff).ToString("x"+j);for(i=26;i++<167;k=Color.FromKnownColor((KnownColor)i),a=n==k.ToArgb()&k.Name.Length<=j?k.Name:a);return a;}

```

Indentation and new lines for clarity:

```
using System.Drawing;
int H(string s,int i,int l)=>Convert.ToInt32(s.Substring(i*l+1,l),16)*(l<2?17:1);
string C(string a){
    int i=17,j=a.Length/3,n;
    var d=a.Split(',');
    Color k,c=a[0]<36
        ?Color.FromArgb(H(a,0,j),H(a,1,j),H(a,2,j))
        :Color.FromName(a);
    c=c.A>0?c:Color.FromArgb(int.Parse(d[0]),int.Parse(d[1]),int.Parse(d[2]));
    j=c.R%i+c.G%i+c.B%i<1?3:6;
    n=c.ToArgb();
    a="#"+(j<6?c.R/i<<8|c.G/i<<4|c.B/i:n&0xffffff).ToString("x"+j);
    for(i=26;i++<167;
        k=Color.FromKnownColor((KnownColor)i),
        a=n==k.ToArgb()&k.Name.Length<=j?k.Name:a
    );
    return a;
}

```

# C#, 265 bytes

Here's the basic solution.

```
using System.Drawing;string C(int r,int g,int b){int i=17,c=r<<16|g<<8|b,j=r%i+g%i+b%i<1?3:6;var o="#"+(j<6?r/i<<8|g/i<<4|b/i:c).ToString("x"+j);for(i=26;i++<167;){var k=Color.FromKnownColor((KnownColor)i);o=c<<8==k.ToArgb()<<8&k.Name.Length<=j?k.Name:o;}return o;}

```

Indentation and new lines for clarity:

```
using System.Drawing;

string C(int r,int g,int b){
    int i=17,
        c=r<<16|g<<8|b,
        j=r%i+g%i+b%i<1?3:6;
    var o="#"+(j<6?r/i<<8|g/i<<4|b/i:c).ToString("x"+j);
    for(i=26;i++<167;){
        var k=Color.FromKnownColor((KnownColor)i);
        o=c<<8==k.ToArgb()<<8&k.Name.Length<=j?k.Name:o;
    }
    return o;
}

```

# Answer
> 8 votes
# Mathematica ~~207 242~~ 500-250=250 bytes

Update:
This works with inputs consisting of rgb triples, color names, or hex numbers.

(12 bit) color-depth output now works fine, thanks to an excellent article on Color Bit Depth Reduction. The basic idea is that, if an RGB triple {r,g,b}, where r, g, and b are in the range of 0-255, (i.e. hex 00-ff) can be represented without loss as a number in the range of 0-15 (i.e. 0-f), then one may use the 3 digit hex number instead of the 6 digit number. Turns out that this will occur whenever 17 (i.e 255/15) divides r, g, and b.

Only built-in functions are used. Mathematica has rules for replacing HTML colors names with RGB triples. For example, one rule is `"Teal"-> RGBColor[0, 128, 128]`. When such rules are inverted, rgb values (recalibrated to the range, {0, 255}) can be replaced with color names.

```
q=ColorData["HTML","ColorRules"];
j=q/.{(c_ -> RGBColor[r_,g_,b_]):> (Floor[255{r,g,b}]-> c)};
k=Reverse/@j;
v@l_:=And@@IntegerQ/@(l/17);
y@l_:=If[v@l,l/17,l];
h@l_:="#"<>(IntegerString[#,16,If[v@l,1,2]]&/@y@l)
o@h_:=Module[{c=(StringLength[h1=StringDrop[h,1]]==6)},FromDigits[#,16]&/@StringPartition[h1,If[c,2,1]]*If[c,1,17]]
u@l_:=ToString[l/.j]
m@s_:=s/.q/.RGBColor[r_,g_,b_]:>Floor[255{r,g,b}]
f@n_:=SortBy[{u@n,h@n},StringLength][[1]]
z@d_:= (If[StringQ@d,If[StringTake[d,1]=="#",e=o@d,e=m@d],e=d];f@e)

```

---

**Examples**

```
z /@ {{0, 0, 0}, {255, 0, 0}, {0, 128, 128}, {139, 0, 0}, {255, 255,
   255}, {72, 61, 139}, {255, 255, 254}, {255, 85, 255}}

```

> {"#000", "Red", "Teal", "#8b0000", "#fff", "#483d8b", "#fffffe","#f5f"}

---

```
z /@ {"Red", "DarkSlateBlue", "Teal", "Black"}

```

> {"Red", "#483c8b", "Teal", "#000"}

---

```
z /@ {"#000", "#f00", "#008080", "#8b0000", "#fff", "#483d8b", "#fffffe", "#f5f"}

```

> {"#000", "Red", "Teal", "#8b0000", "#fff", "#483d8b", "#fffffe", \ "#f5f"}

---

## Commented, Ungolfed Code

(\* rules for replacing a color name with a color swatch, e.g. `RGBColor{255,17,0}`

```
q=ColorData["HTML","ColorRules"];

```

---

(\* rules for replacing a list of 3 integers with the respective color name, if one exists. And the same rules, reversed. \*)

```
rulesListsToColorNames=(q)/.{(c_ -> RGBColor[r_,g_,b_]):> (Floor[255{r,g,b}]-> c)};

rulesColorsToLists=Reverse/@rulesListsToColorNames;

```

---

(\*tests whether a 24 bit hex color can be represented as a 12 bit color with no loss. `reduce` can change the 24 bit expression to a 12 bit expression. \*)

```
depthReducible[l_List]:=And@@IntegerQ/@(l/17);
reduce[l_List]:=If[depthReducible@l,l/17,l];

```

---

(\*RGB list changed to a Hex number \*)

```
fromListToHex[l_List]:="#"<>(IntegerString[#,16,If[depthReducible@l,1,2]]&/@reduce[l])

```

---

(\* Hex number changed to RGB list. \*)

```
fromHexToList[h_String]:=Module[{c=(StringLength[h1=StringDrop[h,1]]==6)},
FromDigits[#,16]&/@StringPartition[h1,If[c,2,1]]*If[c,1,17]
]

```

---

(\* More conversions \*)

```
fromListToColorName[l_List]:=ToString[l/.rulesListsToColorNames]
fromColorNameToHex[s_String]:=fromListToHex[s/.rulesColorsToLists]
fromColorNameToList[s_String]:=s/.q/.RGBColor[r_,g_,b_]:>Floor[255{r,g,b}]

```

---

(\* choses the shortest valid CSS expression of a color \*)

```
f@n_List:=SortBy[{fromListToColorName[n],fromListToHex[n]},StringLength][[1]]

```

---

(\* converts any input into an RGB list and calls `f` \*)

```
returnShortestColor[d_]:=
 (If[StringQ[d],
   If[StringTake[d,1]=="#",
     e=fromHexToList@d,
     e=fromColorNameToList@d],
   e=d];
f@e)

```

# Answer
> 5 votes
# CoffeeScript, ~~411 404 388 384~~ 382/2 = 191

**UPD:** Pretty sure it is final result

Hope, it's okay to use `window.document.*`. Check `rgb` function and `eval` call.

```
s=(c,rgb=(r,g,b)->(2**24+(r<<16)+(g<<8)+b).toString 16)->d=y=document.body;r=(q=(a)->y.style.color=a;d[b='#'+eval(getComputedStyle(y).color)[1...].replace /(.)\1(.)\2(.)\3/,'$1$2$3']=a;b) c;(d='NavyGreenTealIndigoMaroonPurpleOliveGraySiennaBrownSilverPeruTanOrchidPlumVioletKhakiAzureWheatBeigeSalmonLinenTomatoCoralOrangePinkGoldBisqueSnowIvoryRed'.match /.[a-z]+/g).map(q);d[r]||r

```

### Test results

```
rgb(   0,   0,   0 ) -> #000
rgb( 255,   0,   0 ) -> Red
rgb(   0, 128, 128 ) -> Teal
rgb( 139,   0,   0 ) -> #8b0000
rgb(  72,  61, 139 ) -> #483d8b
rgb( 255, 255, 254 ) -> #fffffe
rgb( 255,  85, 255 ) -> #f5f
darkslateblue        -> #483d8b
indigo               -> Indigo
#f00                 -> Red

```

### Commented code

```
s = ( c,
    rgb = ( r, g, b ) ->
        return ( 2 ** 24 + ( r << 16 ) + ( g << 8 ) + b )
        .toString( 16 )
) ->

```

This will save some bytes.

```
    d = y = document.body

```

`q` function will place input color to `document.body.style.color` and get compiled color as `rgb(...)`. Also it will store result as `hexColor:inputColor` in `d`. Notice `eval` use. `rgb(100,100,100)` is a valid JavaScript function call with three number arguments. `rgb` function will convert arguments to single 24/12 HEX notation (like `#fff`, `#f0f0f0`).

```
    r = (
        q = ( a ) ->
            y.style.color = a
            b = '#' + eval( getComputedStyle( y ).color )[ 1... ].replace( /(.)\1(.)\2(.)\3/, '$1$2$3' )
            d[ b ] = a
            return b
    )( c )

```

Split string to array of color names, create lookup object.

```
    ( d = 'NavyGreenTeal...'.match( /.[a-z]+/g )).map( q )

```

And return HEX if no shorter variant in `d`.

```
    return d[ r ] or r

```

# Answer
> 4 votes
# Stylus, ~~238~~ 234/2 = 117

More CSS-like solution! Stylus already has great support for color manipulation, so desired function is pretty small and not golfed a lot.

`f(c){for n in split(' ''navy green teal indigo maroon purple olive gray sienna brown silver peru tan orchid plum violet khaki azure wheat beige salmon linen tomato coral orange pink gold bisque snow ivory red'){lookup(n)==c?c=s(n):c}}`

### Test it here

```
body
  color f(rgb(0, 0, 0))
  color f(rgb(255, 0, 0))
  color f(rgb(0, 128, 128))
  color f(rgb(139, 0, 0))
  color f(rgb(72, 61, 139))
  color f(rgb(255, 255, 254))
  color f(rgb(255, 85, 255))
  color f(darkslateblue)
  color f(indigo)
  color f(#f00)
  color f(rgba(255,0,0,1))
  color f(rgba(255,0,0,0.5))

```

# Answer
> 3 votes
# Matlab 617

A lot of preprocessing and hardcoding. The minimal set of colour names you have to consider are these. Too bad Matlab does not have built in color names=/

```
function s=f(r,g,b);
t=255;
c=[r,g,b];
a=[0 t t;240 t t;245 245 220;t 228 196;0 0 t;165 42 42;t 127 80;0 t t;t 215 0;75 0 130;t t 240;240 230 140;0 t 0;250 240 230;t 165 0;218 112 214;205 133 63;t 192 203;221 160 221;t 0 0;250 128 114;160 82 45;t 250 250;210 180 140;t 99 71;238 130 238;245 222 179;t t t;t t 0];
s=textscan('aqua azure beige bisque blue brown coral cyan gold indigo ivory khaki lime linen orange orchid peru pink plum red salmon sienna snow tan tomato violet wheat white yellow','%s');
i=find(ismember(a,c,'rows'));
k=1;
if i>0;s=s{1}{i};elseif ~any(mod(c,16));k=16;end;d=dec2hex(c/k,2-(k>1))';s=['#',d(:)']

```

# Answer
> 2 votes
# Python 3, ~~857~~ 795 bytes

Having to manually specify all of the accepted colours required did increase the byte count on this one :/

~~`c(a)` takes one argument, `a`, which comes in the form of `rgb(#,#,#)`. From that, the rgb and brackets are removed and the string is then split by commas into an array.~~ `c(x,y,z)` takes 3 ints, the r, g and b values of the rgb colour to process. We put those together in an array `a`. We then use Python's built-in `hex` function which converts a Base 10 number to a Base 16 number on our array and create a hex string (this is done in the `for` loop). The `if` statements convert colours like `000000` to `000`, and replace the known colours using a dictionary.

Here it is (thanks to @undergroundmonorail for tip about `;` in Python):

```
def c(x,y,z):
  a=[x,y,z];b="";
  for i in a:
    i=hex(i)[2:]
    if len(i)<2:i="0"+i;
    b+=i
  k={"00ffff":"AQUA","f0ffff":"AZURE","f5f5dc":"BEIGE","ffe4c4":"BISQUE","0000ff":"BLUE","a52a2a":"BROWN","ff7f50":"CORAL","ffd700":"GOLD","808080":"GRAY","008000":"GREEN","4b0082":"INDIGO","fffff0":"IVORY","f0e68c":"KHAKI","00ff00":"LIME","faf0e6":"LINEN","800000":"MAROON","000080":"NAVY","808000":"OLIVE","ffa500":"ORANGE","da70d6":"ORCHID","cd853f":"PERU","ffc0cb":"PINK","dda0dd":"PLUM","800080":"PURPLE","ff0000":"RED","fa8072":"SALMON","a0522d":"SIENNA","c0c0c0":"SILVER","fffafa":"SNOW","d2b48c":"TAN","008080":"TEAL","ff6347":"TOMATO","ee82ee":"VIOLET","f5deb3":"WHEAT","ffff00":"YELLOW"}
  if b[:3]==b[3:]:b=b[:3];
  if b in k:b=k[b];
  else:b="#"+b;
  return b

```

Old Version:

```
def c(a):
  a=a[4:-1].split(",")
  b=""
  for i in a:
    i=hex(int(i))[2:]
    if len(i)<2:
      i="0"+i
    b+=i
  k = {"00ffff":"AQUA","f0ffff":"AZURE","f5f5dc":"BEIGE","ffe4c4":"BISQUE","0000ff":"BLUE","a52a2a":"BROWN","ff7f50":"CORAL","ffd700":"GOLD","808080":"GRAY","008000":"GREEN","4b0082":"INDIGO","fffff0":"IVORY","f0e68c":"KHAKI","00ff00":"LIME","faf0e6":"LINEN","800000":"MAROON","000080":"NAVY","808000":"OLIVE","ffa500":"ORANGE","da70d6":"ORCHID","cd853f":"PERU","ffc0cb":"PINK","dda0dd":"PLUM","800080":"PURPLE","ff0000":"RED","fa8072":"SALMON","a0522d":"SIENNA","c0c0c0":"SILVER","fffafa":"SNOW","d2b48c":"TAN","008080":"TEAL","ff6347":"TOMATO","ee82ee":"VIOLET","f5deb3":"WHEAT","ffff00":"YELLOW"}
  if b[:3]==b[3:]:
    b=b[:3]
  if b in k:
    b=k[b]
  else:
    b="#"+b
  return "color:"+b+";"

```

Maybe I'll add the bonus to it, I don't know yet. It could definitly do with 50% bytes off!

-Toastrackenigma

# Answer
> 1 votes
# JavaScript (ES6), 499 ~~611~~

*Edit* Added the test cases in the question

Note: I kept just the color names that are shorter than the hex equivalent.

~~Note 2: this can surely be golfed more...~~

```
f=(r,g,b,k='#'+(r%17|g%17|b%17?1<<24|r<<16|g<<8|b:4096|(r*256+g*16+b)/17).toString(16).slice(1))=>
("#d2b48cTAN#f00RED#ff7f50CORAL#f5deb3WHEAT#ff6347TOMATO#ffd700GOLD#008000GREEN#faf0e6LINEN#f5f5dcBEIGE#da70d6ORCHID#4b0082INDIGO#ffc0cbPINK#f0e68cKHAKI#008080TEAL#ee82eeVIOLET#dda0ddPLUM#fa8072SALMON#ffa500ORANGE#a0522dSIENNA#800000MAROON#800080PURPLE#ffe4c4BISQUE#f0ffffAZURE#fffff0IVORY#cd853fPERU#808000OLIVE#c0c0c0SILVER#fffafaSNOW#a52a2aBROWN#000080NAVY#808080GRAY"
.match(k+'([A-Z]+)')||[,k])[1]

// TEST
;[[0,0,0,'#000'],[255,0,0,'red'],[0,128,128,'TEAL'],[139,0,0,'#8B0000'],[72,61,139,'#483D8B'],[255,255,254,'#fffffe'],[255,85,255,'#f5f']]
.forEach(([r,g,b,t])=>(x=f(r,g,b),o+=r+','+g+','+b+' -> '+x+' '+(x.toUpperCase()==t.toUpperCase()?'ok':'error('+t+')')+'\n'),o='')
O.innerHTML=o

function go()
{
  var r,g,b
  [r,g,b] = I.value.match(/\d+/g)
  O.innerHTML=r+','+g+','+b+' -> '+f(r,g,b)+'\n'+O.innerHTML
}
```

```
R,G,B: <input id=I><button onclick="go()">--></button>
<pre id=O></pre>
```

**Less golfed**

```
f=(r,g,b) => (
   k='#'+(
     r%17|g%17|b%17
     ? 1<<24|r<<16|g<<8|b
     : 4096|r/17<<8|g/17<<4|b/17
    ).toString(16).slice(1),
   s = "#d2b48cTAN#f00RED#ff7f50CORAL#f5deb3WHEAT#ff6347TOMATO#ffd700GOLD#008000GREEN#faf0e6LINEN#f5f5dcBEIGE#da70d6ORCHID#4b0082INDIGO#ffc0cbPINK#f0e68cKHAKI#008080TEAL#ee82eeVIOLET#dda0ddPLUM#fa8072SALMON#ffa500ORANGE#a0522dSIENNA#800000MAROON#800080PURPLE#ffe4c4BISQUE#f0ffffAZURE#fffff0IVORY#cd853fPERU#808000OLIVE#c0c0c0SILVER#fffafaSNOW#a52a2aBROWN#000080NAVY#808080GRAY",
   m = s.match(k+'([A-Z]+)'), // names are upper, hex codes are lower
   (m || [,k])[1] // if no match use the code
)

```

# Answer
> 1 votes
## Python 3 + matplotlib, 193 bytes

```
import matplotlib.colors as M
def f(c):
 H=h=M.rgb2hex([i/255for i in c]).upper()
 if all(v%17<1for v in c):h=h[::2]
 for n,x in M.CSS4_COLORS.items():
  if H==x and len(n)<len(h):h=n
 return h

```

Input is taken as a tuple or array of integers.

**Try it here**

### Less golfed:

```
import matplotlib.colors as mcolors

def f(c):
  # Save two copies of the uppercase hex value.
  # Inconvenient, but it takes decimals instead of integers,
  # and it returns lowercase, but the dictionary has uppercase. :'(
  H=h=mcolors.rgb2hex([i/255 for i in c]).upper()

  # Check if all 3 integers are divisible by 17,
  # because that means in hex the digits are the same,
  # similar to how that works for multiples of 11 in base 10,
  # or multiple of N+1 in base N.
  if all(v%17<1 for v in c):
    # Get every other character from the hex string
    h=h[::2]

  # Loop through the dictionary. Way too verbose for me to appreciate.
  for n,x in mcolors.CSS4_COLORS.items():
    # If the name is shorter, use it.
    # H is needed, because "h" is the shortened.
    if H==x and len(n)<len(h):h=n

  return h

```

`CSS4_COLORS` contains a dictionary of the color names and hex values. Unfortunately, the dictionary is "backwards" from what I'd like. Also, this could likely be used to create a better score using the bonus, though I don't think it'd win.

---
Tags: code-golf, css
---


title: backwardS_hybriD-snakE_kebaB-cameL_case

text:
# Question
Title: backwardS_hybriD-snakE_kebaB-cameL_case
There are a bunch of different casing conventions, like `camelCase`, `PascalCase`, `snake_case` etc. It's annoying juggling all of these, so instead of choosing one like a sensible person, why not cursedly mix all of them together?

Your challenge is to, given a list of words (only containing lowercase letters), convert them to backwardS\_hybriD-snakE\_kebaB-cameL\_case. To do so:

* The words are joined by alternating underscores and hyphens, starting with underscores.
* Capitalise the last letter of every word but the last.

This is , shortest wins!

## Testcases

These are formatted as space-separated words

```
hello world -> hellO_world
beans -> beans
one two three four -> onE_twO-threE_four
backwards hybrid snake kebab camel case -> backwardS_hybriD-snakE_kebaB-cameL_case
test three words -> tesT_threE-words
o n e l e t t e r -> O_N-E_L-E_T-T_E-r

```

# Answer
> 13 votes
# Python, 72 bytes

```
lambda s:re.sub(" (.*?) ",r"_\1-",s+"x ")[::-1].title()[:1:-1]
import re
```

Attempt This Online!

#### How?

Uses regular expression to substitute pairs of spaces. To make sure every space is handled the auxiliary string "x " is appended. The result is reversed, `title` cased and reversed back. The auxiliary string (which has absorbed one unwanted `title` casing) is removed.

# Answer
> 11 votes
# JavaScript (ES6), 50 bytes

Expects and returns a list of ASCII codes.

```
a=>a.map((c,i)=>a[i+1]^32?c^32?c:C^=114:c^32,C=45)

```

Try it online!

### Commented

```
a =>              // a[] = list of ASCII codes
a.map((c, i) =>   // for each value c at position i in a[]:
  a[i + 1] ^ 32 ? //   if the next character is not a space:
    c ^ 32 ?      //     if the current character is not a space:
      c           //       leave it unchanged
    :             //     else:
      C ^= 114    //       make C switch between '-' and '_' and use it
  :               //   else:
    c ^ 32,       //     inverse the case of the current character
  C = 45          //   start with C = 45 (i.e. '-')
)                 // end of map()

```

# Answer
> 7 votes
# Retina, 13 bytes

```
Y`l  `L\_-`.

```

Try it online! Link includes test cases. Explanation: Cyclically transliterates each space and the lower case letter before it. Since the two transliteration strings are the same length and the lower case letters appear exactly once each (via the shorthand `l`) they are simply transliterated to the upper case letters (`L`), however, there are two spaces in the transliteration string so they get alternately transliterated to `_` (which needs to be escaped in a transliteration) and `-` (which fortunately doesn't need to be escaped at the end of a string.)

The best I could do in Retina 0.8.2 was 23 bytes:

```
T`l `L\_`.
(_.+?)_
$1-

```

Try it online! Link includes test cases. Explanation: Since Retina doesn't have cyclic transliteration I just transliterate all of the spaces to `_`s and then fix up alternate `_`s to `-`s afterwards (which has to be done longhand as Retina 0.8.2 doesn't have step limits either).

# Answer
> 7 votes
# JavaScript, 52 bytes

-3 bytes by emanresu A; -2 bytes by Arnauld.

```
s=>s.replace(/. /g,c=>c[0].toUpperCase()+'-_'[s^=1])

```

Try it online!

# Answer
> 5 votes
# Vyxal `s`, 12 bytes

```
ṫ$RǐR₅‛_-ẎYp

```

Try it Online!

-5 bytes thanks to emanresuA

## How?

```
ṫ$RǐR₅‛_-ẎYp
ṫ            # Tail extract, push a[:-1] and a[-1]
 $           # Swap
  R          # Reverse each
   ǐ         # Capitalize first letter of each
    R        # Reverse each
     ₅       # Push length without popping
      ‛_-    # Push "_-"
         Ẏ   # Extend this string to the length
          Y  # Interleave the list of words and each character of this string together
           p # Append the last item of the input (pushed earlier by tail extract) to this list
             # s flag joins this list to a string

```

# Answer
> 5 votes
# APL (Dyalog Extended), 25 bytes

Anonymous tacit prefix function. Takes list of words.

```
1⌊⍢⊃⍤↓⍢⌽∘∊⌈⍢⊃⍢⌽¨,¨'_-'⍴⍨≢

```

Try it online!

tally of words

`'_-'⍴⍨` use that to cyclically reshape this string

concatenate each of those to each of the following:

…`¨` on each word:

…`⍢⌽` while reversed (reverse back again when done):

…`⍢⊃` while the first character is extracted (put it back again when done):

uppercase

`∘∊`**e**nlist (flatten), and then:

…`⍢⌽` while reversed (reverse back again when done):

`1``⍤↓` drop the first character, and then:

…`⍢⊃` while the first character is extracted (put it back again when done):

lowercase

# Answer
> 4 votes
# Pyth, 16 bytes

```
ts.e+@"-_"k_r_b3

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 13 bytes

```
í™í`l)„_-ÞøS¨

```

Input as a list of words; output as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
í             # Reverse each word in the (implicit) input-list
 ™            # Titlecase each reversed word
  í           # Reverse each back
   `          # Pop the list, and push all words separated to the stack
    l         # Lowercase the last/top one
     )        # Wrap the stack back into a list
      „_-     # Push string "_-"
         Þ    # Cycle it indefinitely: ["_","-","_","-","_","-",...]
          ø   # Create pairs of the two lists, ignoring trailing items of the
              # longer (in this case infinite) list
           S  # Convert this list of pairs to a flattened list of characters
            ¨ # Remove the trailing "_"/"-"
              # (after which the result is output implicitly)

```

# Answer
> 3 votes
# Python, ~~86~~ 80 bytes

```
lambda s,i=0:"".join("_-"[i:=~i]+w.title()for w in s[::-1].split())[:1:-1]+s[-1]
```

Attempt This Online!

-6 bytes thanks to @xnor

# Answer
> 3 votes
# Charcoal, 24 bytes

```
⭆θ⎇⁼ §θ⊕κ↥ι⎇⁼ ι§_-№…θκ ι

```

Try it online! Link is to verbose version of code. Explanation: Similar approach to @Arnauld's JavaScript answer.

```
 θ                          Input string
⭆                           Map over characters and join
  ⎇⁼ §θ⊕κ                   If next character is a space then
         ↥ι                 Current character uppercased
           ⎇⁼ ι             Else if current character is a space then
               §_-          Literal string `_-` cyclically indexed by
                  №…θκ      Number of spaces in current prefix
                       ι    Else current character
                            Implicitly print

```

I also tried an approach based on splitting and joining but I wasn't able to get it below 26 bytes.

# Answer
> 3 votes
# MathGolf, 19 bytes

```
mxδmxhû_-*▒^\£<─~;!

```

Input as a list of words.

Try it online.

**Explanation:**

```
mx                  # Reverse each words in the (implicit) input-list
  δ                 # Titlecase each word
   mx               # Reverse each word back
     h              # Push the length of the list (without popping)
      û_-           # Push string "_-"
         *          # Repeat it the length amount of times
          ▒         # Convert it to a list ["_","-","_","-",...]
           ^        # Zip the two lists together, creating pairs
                    # (including trailing ["_"],["-"] items)
            \       # Swap to get the input-list again
             £      # Pop and push its length
              <     # Only leave that many items (to only keep the pairs, and
                    # removing the trailing ["_"],["-"] items)
               ─    # Flatten this list of pairs
                ~   # Dump all strings separated to the stack
                 ;  # Discard the top ("_"/"-") one
                  ! # Lowercase the last/top word
                    # (implicitly join and output the entire stack)

```

# Answer
> 3 votes
# brev, ~~161~~ 150 bytes

```
(fn(strse x (: word(neg-look-ahead eos))(as-list(fn `(,@(butlast x) ,(char-upcase(last x)))))(: ($ word)" "($ word)" ")(conc(m 1)"_"(m 2)"-")'" ""_"))

```

325 with white space and test cases added:

```
(map
 (fn (strse x (: word (neg-look-ahead eos))
            (as-list (fn `(,@(butlast x) ,(char-upcase (last x)))))
        (: ($ word) " " ($ word) " ")
        (conc (m 1) "_" (m 2) "-")
        '" " "_"))
 '("hello world"
   "beans"
   "one two three four"
   "backwards hybrid snake kebab camel case"
   "test three words"
   "o n e l e t t e r"))

```

# Answer
> 3 votes
## Python 3, 165 bytes

This is my first time having a go at this, so my answer is not gonna be great, but I found this really fun

```
lambda w:"".join([b if not i%2 else b[1:-1] for i,b in enumerate("_/-".join([s[::-1].title()[::-1] for s in w[:-1]]+[w[-1]]).split("/"))])+w[-1][::-1][:(len(w)+1)%2]

```

# Answer
> 2 votes
# Factor, ~~89 84~~ 75 bytes

```
[ unclip [ odd? "-""_"? rot 1 cut* >upper append -rot glue ] reduce-index ]

```

Try it online!

# Answer
> 2 votes
# QuadR `2g`, ~~37~~ ~~30~~ 29 bytes

Takes space-separated words.

```
(\S)
_(.*)(\S)_
\u1_
_\1\u2-

```

Try it online!

PCRE **R**eplace as follows, `2` times, with non-`g`reedy patterns:

| Target | Replacement |
| --- | --- |
| `(\S)`  non-space followed by space | `\u1_` uppercased non-space followed by underscore |
| `(.*?)(\S)_` any run of characters followed by a non-space and an underscore | `_\1\u2-` an underscore, the run, the uppercased non-space, an underscore |

# Answer
> 2 votes
# C (gcc), ~~109~~ 91 bytes

*-18 bytes thanks to @ceilingcat*

```
main(c,v)char**v;{for(;1[++v];c=!c)strlen(*v)[*v-1]-=32,printf(c?"%s_":"%s-",*v);puts(*v);}

```

Try it online!

# Answer
> 2 votes
# Zsh, 61 bytes

```
g()<<<${${4+${3%?}${3[-1]:u}$1`g $2 $1 ${@:4}`}:-$3}
g _ - $@

```

Try it online!

Recursive solution:

```
g() # define function g (braces optional since body is one line)
    <<<${${4+${3%?}${3[-1]:u}$1`g $2 $1 ${@:4}`}:-$3}
#        ${4+                                  }      # if $4 is set, substitute
#            ${3%?}                                   #   $3, remove last character
#                  ${3[-1]:u}                         #   upper last character of $3
#                            $1                       #   $1 (either _ or -)
#                              `g $2 $1 ${@:4}`       #   recurse, swapping _ and -
#      ${${                                   }:-$3}  # else substitute $3 unchanged
#   <<<                                               # print
g _ - $@   # seed initial arguments

```

# Answer
> 2 votes
# Python 3, 95 bytes

Honestly not a great submission, but I can't figure out a way to make it any smaller with this approach.

```
lambda l:''.join('-_'[i%2]+w[:-1]+(w[-1].upper(),w[-1])[i>len(l)-2]for i,w in enumerate(l))[1:]

```

Try it online!

# Answer
> 2 votes
# Perl 5 \+ `-p055`, 26 bytes

```
s!(.) !uc$1.($|--?$/:_)!eg
```

Try it online!

# Answer
> 2 votes
# \>\<\>, ~~32~~ 30 bytes

```
55*ii:48*=?\$o30.
-{:0$-}"F"+\

```

Try it online

**Explanation**

```
55*i               # init stack with 25 and first input
    i:48*=?\       # if next input is 32, move to row 2
            $o30.  # else print previous input and jump to next input handling
-                  # subtract 32 from previous input (switch to uppercase)
 {:0$-}            # get the 25 from bottom of stack and negate a copy for next iteration
       "F"+        # add "F" to get either "-" or "_" depending on sign of the 25
           \       # move back to row 1 to print

```

# Answer
> 1 votes
# Ly, ~~25~~ 37 bytes

```
i0"_-"rsp[' =:' *lf-o[Ifprfr0]psp]>lo

```

Try it online!

Revised code... I didn't read the rule saying space has to be translated to `-` and `_` alternating.

```
i                                     - read input as codepoints
 0"_-"                                - push "0" and delimiters
      r                               - reverse stack
       sp                             - save last and delete
         [                      p]    - loop over the 2-N chars
          ' =                         - push 0|1 from comparing curr char to " "
             :                        - duplicate result
              ' *                     - multiply result w/ " " (32)
                 lf                   - pull prev char, flip top stack entries
                   -                  - capitalizes if the curr char is " "
                    o                 - write out char codepoint as a char
                     [      0]p       - if/then, true if " " is curr char
                      I               - copy second to bottom stack entry                fp             - pull " " forward, delete
                         rfr          - reverse bottom two entries
                               s      - stash "_" or "-"
                                  >   - switch stacks
                                   lo - load last char and print

```

# Answer
> 1 votes
# BQN, 30 bytes

```
1↓·∾≠⊸⥊⟜"-_"∾¨-⟜32⌾⊏⌾⌽¨⌾(¯1⊸↓)

```

Try it here!

## Explanation

* `...¨⌾(¯1⊸↓)` for each non-last word of the input...
    + `-⟜32⌾⊏⌾⌽` uppercase last letter (literally by reversing and subtracting 32 from the first char)
* `≠⊸⥊⟜"-_"∾¨` couple each word with alternations of `-` and `_`
* `1↓·∾` join and drop first character

# Answer
> 1 votes
# sed w/ -E flag, 43 bytes

```
s/(.) /\U\1_/g
s/([^_]*_){2}/\0-/g
s/_-/-/g
```

Attempt This Online!

# Answer
> 1 votes
# PowerShell Core, 154 bytes

```
filter f([char[]]$r){$s="_","-"
($r|%{[string]$c=$_
if(" "-eq$r[$i+1]){$c.ToUpper()}elseif(" "-eq$_){$s[$x+0]
$x=($x+1)%2}else{$c.ToLower()}$i++})-join''}

```

Try it online!

Ungolfed:

```
filter f (
    [char[]]$r                     # coerce input string to character array
) {
    $s = "_","-"                   # initialize space array to replace " " with "_" and "-"
    (                              # () needed for -join ''
        $r | ForEach-Object{
            [string]$c=$_          # [char] lacks .ToUpper(), .ToLower() - coerce back to [string]
            if(" " -eq $r[$i+1]){  # if next character in array is a space
                $c.ToUpper()       # RETURN uppercase
            }
            elseif(" " -eq $_){    # if space is the current character
                $s[$x+0]           # RETURN indexof space array. incl. "+0" in the index depth so we don't need to initialize $x
                $x=($x+1)%2        # x++ but modulus 2
            }
            else{
                $c.ToLower()       # RETURN lowercase
            }
            $i++                   # increment $i for lookahead
         }
     )-join''                      # [char[]] back to [string]. implicit RETURN from function
 }

```

# Answer
> 1 votes
# Pip, 20 bytes

```
aR`. `{UC@a."_-"@Uv}

```

Takes input as a single command-line argument with words space-separated. Attempt This Online!

### Explanation

```
aR`. `{UC@a."_-"@Uv}
a                     Command-line argument
 R                    Replace
  `. `                matches of this regex: any character followed by a space
      {            }  With this callback function:
          a             The matched string
         @              's first character
       UC               Uppercased
           .            Concatenated to
                  v       A number, initially -1
                 U        Increment
                @         and use as a cyclical index into
            "_-"          That string

```

# Answer
> 0 votes
# Ruby `-p`, 39 bytes

```
gsub(/(.) /){$1.upcase+"_-"[($.+=1)%2]}

```

Attempt This Online!

# Answer
> 0 votes
# Japt, 18 bytes

```
®ou qÃov
ò mq'_ q-

```

Try it

Input as an array of character arrays.

Explanation:

```
®ou qÃov
®    Ã    # For each word in the input:
 ou       #  Convert the last letter to uppercase
    q     #  Join to a string
      o   # For the last word:
       v  #  Convert it to lowercase
          # Save as U

ò mq'_ q-
ò         # Cut U into pairs of words
  m       # For each pair:
   q'_    #  Join to a single string with "_" in between
       q- # Join all those strings with "-" between

```

# Answer
> 0 votes
# Japt `-hP`, 16 bytes

Takes input as a 2D character array.

```
ÇiUËouÃíUî"_-"¹c

```

Try it

```
ÇiUËouÃíUî"_-"¹c     :Implicit input of 2D character array U
Ç                    :Pop last element, pass it through the following function & push back
 i                   :  Prepend
  UË                 :    Map the remaining elements of U
    o                :      Modify last
     u               :        Uppercase
      Ã              :    End map
       í             :    Interleave
        Uî"_-"       :      Mould "_-" to length of U
              ¹      :  End prepend
               c     :  Flatten
                     :Implicitly join and output last element

```

---
Tags: code-golf, string
---


title: Molding ASCII art

text:
# Question
Title: Molding ASCII art
You are given a single printable ASCII string containing no newlines, and a multiline "mold", containing spaces (), and hashes (`#`).

You must go character by character in the string, and replace **hashes** using the characters from the string in left-right, top-bottom order. If the string is too short to fill the mold, you stop outputting, if the string is too long you truncate the string to exactly fill the mold.

---

Example string/mold (string too long, truncated):

```
Loremipsumdolorsitamet,consecteturadipiscingelit.Namsuscipitmagnanoneratgravidacondimentum.Vestibulumnecnisllorem.Fuscemolestieviverranibh,eueleifendnislplaceratnon.Namblanditturpislacus,vitaemolestielacusimperdietquis.Nullapulvinar,exquissollicitudinfacilisis,eratnullavolutpatlectus,etluctusenimvelitegetex.Inhachabitasseplateadictumst.Donecinterdumnullalacinia,sodalesloremin,eleifendturpis.Pellentesqueanisimi.Aeneannonlobortisdiam,quisaliquetquam.Aeneanaugueipsum,imperdietsedaliquetnon,volutpategetsapien.Nullampharetranullaquispretiumornare.Aliquamfermentumvestibulummassavitaevehicula.
###########################################################
##### ##############   ###### ###### ######################
#####  ##   ######   #  ##### ###### ########        ######
###### #  #  ####  #### ##### ###### #######  ######  #####
######   ###  ###       ##### ###### ####### #######  #####
######  ##### ### ########### ###### #######   ###   ######
###### ###### ###  ########## ######      #####   #########
##################       ####    ##########################
###########################################################

```

Example output:

```
Loremipsumdolorsitamet,consecteturadipiscingelit.Namsuscipi
tmagn anoneratgravid   acondi mentum .Vestibulumnecnisllore
m.Fus  ce   molest   i  evive rranib h,euelei        fendni
slplac e  r  atno  n.Na mblan dittur pislacu  s,vita  emole
stiela   cus  imp       erdie tquis. Nullapu lvinar,  exqui
ssolli  citud inf acilisis,er atnull avolutp   atl   ectus,
etluct usenim vel  itegetex.I nhacha      bitas   seplatead
ictumst.Donecinter       dumn    ullalacinia,sodalesloremin
,eleifendturpis.Pellentesqueanisimi.Aeneannonlobortisdiam,q

```

Example string/mold (string too short, output stopped):

```
This probably won't look good.
### ### ### ###
# # # # #   #
### ### #   # #
#   #   #   # #
#   #   ### ###

```

Corresponding output:

```
Thi s p rob abl
y   w o n   '
t l ook     g o
o   d   .

```

---

Shortest code in bytes wins.

Credit for the idea to this website.

# Answer
> 5 votes
## CJam, ~~16~~ 14 bytes

*Thanks to Sp3000 for saving 2 bytes.*

```
lq{s'#-\+(\}/;

```

Terminates with an error if the string is too short, but the error is printed to STDERR.

Try it online!

Alternatively (same byte count):

```
lq{SN+&\+(\}/;

```

### Explanation

```
l       e# Read the input line.
q       e# Read the grid.
{       e# For each character in the grid...
  s     e#   Convert to string.
  '#-   e#   Remove "#" from it.
  \+    e#   Prepend it to the input line (this is a no-op for "#"s in the grid).
  (     e#   Pull off the first character from the input line. This will terminate the
        e#   program with an error once the input line is empty.
  \     e#   Swap the character with the input line.
}/
;       e# Discard the remainder of the input line if there is any.

```

# Answer
> 9 votes
# LabVIEW, 37 LabVIEW Primitives

splits the string into text and mold then transforms them into an array. Checks the mold if theres a # and puts a char from text else it does nothing. If either the text or the mold are empty exit the loop

# Answer
> 7 votes
# Haskell, 48 bytes

called like "(replace with string)#(hashmark string)":

```
[]#_=[]
(r:t)#('#':s)=r:t#s
r#(c:s)=c:r#s
_#_=[]

```

Less golfed:

```
combine replacements slots | null replacements = []
                           | null slots        = []
                           | head slots == '#' = head replacements : combine (tail replacements) (tail slots)
                           | otherwise         = head slots        : combine       replacements  (tail slots)

```

# Answer
> 5 votes
## Retina, ~~42~~ 40 bytes

Byte count assumes ISO 8859-1 encoding.

```
T`#`×`¶.+
+`^(.)([^×]+)×
$2$1
^.*¶|×\D*

```

The trailing linefeed is significant.

Try it online!

### Explanation

```
T`#`×`¶.+

```

We first replace `#` which are part of the grid with the non-ASCII (but extended ASCII) character `×` so we don't confuse them with any `#` that might appear on the first line.

```
+`^(.)([^×]+)×
$2$1

```

Now we fill as many `×` as possible from the first line by repeatedly replacing the first `×` we can find with the first character on the first line (which is removed in the process).

```
^.*¶|×\D*

```

Finally, we get rid of anything that's left on the first line as well as anything from the first `×` to truncate the input in both directions.

# Answer
> 4 votes
# JavaScript (ES6), ~~57~~ ~~56~~ 55 bytes

```
(s,m)=>m.replace(x=/[^]/g,c=>c-1?x&&c:x=s[i++]||"",i=0)

```

*Saved 1 byte thanks to @Neil!*

## Explanation

Works with hashes in the input string and retains trailing white-space after the input string has finished.

```
var solution =

(s,m)=>
  m.replace(x=/[^]/g,c=> // for each character c of the mold, initialise x to true
    c-1?                 // if c is a space or newline:
      x&&c               // if x is truthy, return c
                         // else if the string has ended, x will equal "" (false), return x
    :                    // else if c is a hash:
      x=                 // set x to the character of the input string
        s[i++]||"",      // return the input string character (or "" if finished)
    i=0                  // initialise i to 0
  )
```

```
<input type="text" id="input" value="This probably won't look good." /><br>
<textarea id="mold" rows="6" cols="40">### ### ### ###
# # # # #   #
### ### #   # #
#   #   #   # #
#   #   ### ###</textarea><br>
<button onclick="result.textContent=solution(input.value,mold.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 3 votes
# Python 3, ~~69~~ ~~68~~ 67 bytes

```
def f(s,m):s=iter(s);return''.join(n<'#'and n or next(s)for n in m)

```

`Ideone`

Thanks to FryAmTheEggman, Chiel ten Brinke for the byte off. Alternatively, I could have used Python 2 for an extra one (`print` without `()`).

# Answer
> 2 votes
# pb, 359 bytes

```
^w[B!0]{w[B=10]{t[T+1]b[0]}>}<w[T!0]{w[B!0]{<}>^b[T]vw[B!0]{t[B]b[0]^v[B]v<[X]w[B!0]{>}b[T]<[X]^[Y+2]w[B=0]{>}t[B]b[0]>b[T]v}^t[B-1]vw[B=0]{<}}>b[10]t[X]w[X!-2]{w[B!0]{v}<}w[X!T]{b[35]>}^[Y]^<[X]w[B!10]{t[B]b[0]w[T=35]{t[10]}v<[X]w[B!35]{w[B=0]{v<[X]<b[1]}>}b[T]^[Y]^<[X]w[B=0]{>}}<[X+2]w[B=0]{v}w[B!0]{b[0]>}w[Y!-1]{<[X]^w[B!0]{w[B=35]{b[0]}w[B=10]{b[35]}>}}

```

In pb, input is strictly one dimensional. It doesn't understand that you're drawing a shape with your input, it just sees one long line with some bytes with a value of 10 thrown in there. The first thing this program does is copy all but the first "line" of input onto Y=0, Y=1, etc, to create the shape of the mold.

Something I've noticed a lot in code golf, but *especially* when golfing esoteric languages, is that you often don't want to have two branches to deal with; you just set yourself up that you do the same thing in either case. The naive way to solve this problem would probably check the length of the string against the number of hashes in the rest of the input and do something depending on the result, because it has to behave differently depending on what gets cut off. But that's a lot of bytes.

Instead, after completing the mold, an extra line is added to the bottom. It is simply `n` hashes in a row, where `n` is the length of the string. Now the string is guaranteed to fit! After inserting all the characters of the string, that extra line that was added is unconditionally destroyed. Any leftover hashes in the mold proper are erased as well, and that's the necessary output!

Of course, it would violate the spec to simply destroy all hashes. After all, there could be a hash in the input string! To handle this, I refer to another part of the spec:

> You are given a single printable ASCII string **containing no newlines**

(Emphasis mine.) By the time we're dealing with the string, we don't really care if there are newlines in it, but we do know that there aren't any. So, all hashes are replaced with newlines before being put into the mold! After all hashes are destroyed, all newlines are replaced with hashes again. This doesn't turn the entire output into a single hash-delimited line because the nature of pb's 2D output means that it never actually put a newline at the end of each line, it just went on to the next line.

**Ungolfed:**

```
# Start by copying down the mold
^
# (B means "the character under the cursor")
w[B!0]{       # While B isn't a null byte:
    w[B=10]{    # While B IS a newline:
            t[T+1]    # Increase T by 1
                      # (`T` is the only variable that can be modified directly)
            b[0]      # Overwrite with 0 to break out of inner loop
    }
    >           # Move to the right
                # (dodge the 0 we wrote and progress towards the end of input)
}

# Brush is now at the end of the input, T contains number of lines

<             # Make sure the brush is actually /on/ the input
w[T!0]{       # While T isn't 0:
    w[B!0]{<}>  # Go to the first character of the last line
    ^b[T]       # Place a flag above current character
                # Also a convenient way to get the value of T back later
    vw[B!0]{    # While the character under the flag isn't 0:
            t[B]b[0]  # Put it in T, overwrite with 0
            ^v[B]v    # Go down by the amount written in the space above
            <[X]      # Go left by the amount right the brush is (i.e. go to X=0)
            w[B!0]{>} # Find first empty space
            b[T]      # Write the value of T
            <[X]      # Go left by the amount right the brush is
            ^[Y+2]    # Go up by the amount down the brush is plus 2 (above input)
            w[B=0]{>} # Find flag
            t[B]b[0]  # Pick it up, overwrite with 0
            >b[T]     # Place it to the right
    v}
    ^t[B-1]v    # Collect flag - 1
    w[B=0]{<}   # Go to end of previous line
}

# Mold is placed, all that's left is placing the string
>b[10]        # Put a newline at the end, guaranteed to not be in the string
t[X]          # Save current X value in T

# Add more hashes, guaranteed to fit the input and findable later
w[X!-2]{       # While X!=-2:
    w[B!0]{v}    # Move down until hitting a null byte
    <            # Move left
}
w[X!T]{        # While not at the X value we saved earlier:
    b[35]>       # Travel right, leaving hashes
}

^[Y]^<[X]     # Go to (0, -1)

w[B!10]{      # Until hitting the newline at the end:
    t[B]b[0]    # Pick up character, overwrite with 0
    w[T=35]{    # If it's a hash...
            t[10]     # Make it a newline so we remember, deal with it later
    }
    v<[X]       # Go to (0, 0)
    w[B!35]{    # While B is not a hash:
            w[B=0]{   # While B IS null:
                    v       # Go down
                    <[X]<   # Go to X=-1
                    b[1]    # Print a 1 to break loop (it won't be rendered anyway)
            }
            >           # Go right, either ignore a non hash or go to X=0
    }
    b[T]        # Overwrite hash with picked up character
    ^[Y]^<[X]   # Go to (0, -1)
    w[B=0]{>}   # Go to first character of it to restart loop
}

<[X+2]        # Go to (-2, -1)
w[B=0]{v}     # Go down until finding the row of added hashes
w[B!0]{b[0]>} # Wipe it out unconditionally
w[Y!-1]{      # For every remaining line on the screen:
    <[X]^       # Go to the beginning
    w[B!0]{     # For each character in it:
            w[B=35]{  # If it's a hash:
                    b[0]    # Destroy it
            }
            w[B=10]{  # If it's a newline:
                    b[35]   # Write a hash (after the check to destroy hashes!)
            }
    >}
}

```

# Answer
> 1 votes
## ES6, 59 bytes

```
(t,m)=>m.replace(/#/g,h=>t[i++]||h,i=0).replace(/#[^]*/,'')

```

70 bytes if the text can contain hashes:

```
(t,m)=>m.replace(/#/g,(_,n)=>t[i]&&(j=++n)&&t[i++],i=0,j=0).slice(0,j)

```

# Answer
> 1 votes
## Perl, ~~53~~ ~~51~~ 42 + 2 = 44 bytes

```
@a=/./g;$/="";$_=<>;s/#/shift@a/ge;s/\s+$//

```

Requires `-p` to run. Explanation:

```
@a=/./g; # Split first line into an array of characters
$/=""; # Enable slurp mode (read the rest of lines in one go)
$_=<>;
s/#/shift@a/ge;
s/\s+$//
# With '-p' auto print is enabled

```

# Answer
> 1 votes
# Jelly, ~~10~~ 8 bytes

```
¹ƈ<”#$?€

```

Try it here!

# Answer
> 1 votes
# Perl 6, 72 bytes

```
my@a=get.comb;say(S:g/\#/{@a.shift//''}/~~{S/\s+$//}),@a||last for lines

```

# Answer
> 1 votes
# ES6, 47 bytes

Probably the most straightforward solution.

```
(S,R)=>(i=-1,S.replace(/#/g,_=>R[++i]||R[i=0]))

```

This code creates an anonymous function that receives 2 parameters and returns the final result.

The first parameter `S` is the "map" string with your `"#"`, while the second parameter `R` is the "replacement" for those `"#"`.

# Answer
> 1 votes
# Ruby, 52 bytes

```
->a,b{i=-1
a.gsub(/(#)|./){b[i+1]?$1?b[i+=1]:$&:""}}

```

Attempt This Online!

# Answer
> 1 votes
# Julia 1.0, ~~98 88~~ 77 bytes

```
!S=((a,b)=split(S,'
';limit=2);j=0;[b...].|>m->(print(m=='#' ? a[j+=1] : m)))

```

Try it online!

-22 MarcMush

# Answer
> 1 votes
# K (ngn/k), 39 bytes

```
{(w@l)#@[y;l#w;:;(l:(#x)&#w:&"#"=y)#x]}

```

Try it online!

Explanation:

```
{(w@l)#                                 / up to the final index
       @[y;                             / replace the mold
           l#w;:;                       / at the first l indices of hash characters
                 (l:(#x)&#w:&"#"=y)     / where l is the min of
                                          number of such indices and length of string
                                   #x]} / with the first l characters of string

```

Uses the fact that one past the last index of a list is null and taking the first null characters defaults to the full list.

# Answer
> 0 votes
# Python 3

# ~~152~~ 127 bytes

A full program.

```
from sys import stdin as S
s=list(S.readline())
print(''.join([''if not s else(s.pop(0)if m=='#'else m)for m in S.read()]))

```

# 106 bytes

A function that takes the stream as input.

```
def f(S):s=list(S.readline());return''.join([''if not s else(s.pop(0)if m=='#'else m)for m in S.read()])

```

# Answer
> 0 votes
# 05AB1E, 12 bytes

```
`'ÿ«)'#s.;'ÿ¡н

```

Also complies to the two rules in the comments, unlike some of the other answers:

1. The input-sentence can contain hashes and (potentially trailing) spaces.
2. The output does not contain trailing spaces (unless the input contained trailing spaces), only a single trailing newline.

Try it online.

**Explanation:**

I take advantage of the fact that the input only contains printable ASCII.

```
`               # Push the characters of the first (implicit) input-sentence separately
                # to the stack
 'ÿ«           '# Append an "ÿ" to the last character
    )           # Wrap the entire stack into a list
     '#        '# Push string "#"
       s        # Swap so the list is at the top again
        .;      # Replace every first "#" in the second (implicit) multi-line string
                # with the items in the list one by one
          'ÿ¡  '# Split the resulting string on "ÿ"
             н  # Only keep the first part
                # (after which the result is output implicitly with trailing newline)

```

Unfortunately the legacy version of 05AB1E doesn't vectorize with builtin `.;`, otherwise the second `'ÿ` could have been replaced with `Z` (maximum character - based on codepoint - without popping). In the new 05AB1E version, the min/max builtins doesn't work on characters. But because it doesn't vectorize, it's 15 bytes instead: ``'ÿ«)v'#y.;}Z¡н` \- try it online.

# Answer
> 0 votes
# Python, 64 bytes

```
f=lambda s,m:m and(z:=m[0]*(m[0]!='#')+s)and z[0]+f(z[1:],m[1:])

```

Attempt This Online!

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


title: Perfect Nontransitive Sets

text:
# Question
Title: Perfect Nontransitive Sets
## Background

For the purposes of this challenge, we'll define a "perfect nontransitive set" to be a set \\$A\\$ with some irreflexive, antisymmetric relation \\$\<\\$, such that for all \\$a \in A\\$ we have that \\$|\\{x \in A|x\<a\\}|=|\\{x \in A|x\>a\\}|\\$.

Okay, now in layperson's terms: \\$A\\$ is a set of elements with no duplicates. \\$\<\\$ is a comparison on the elements of \\$A\\$ which is true in exactly one direction unless comparing two equal elements (in which case it is false both ways). For every element \\$a\\$ of \\$A\\$ there must be an equal number of elements in \\$A\\$ greater than and less than \\$a\\$ (neither of these lists include \\$a\\$ itself).

## The Challenge

Given an input \\$n\\$ your job is to output one (or many) perfect nontransitive set(s) of size \\$n\\$ where the elements are tuples of 3 integers. You may assume that \\$n\>0\\$ will be odd. The comparison operation you must use is "majority rules", so in comparing two tuples we'll compare them element-wise and whichever there's more of "less-thans" or "greater-thans" will determine the overall result. All pairs of elements in your set must be comparable, that is, one must be "less than" the other. Note that while this allows you to have tuples where some elements are equal, it will likely be easier to exclude such pairs. Here are some more worked out example comparisons for reference:

```
0<1  0<1  1>0 -> (0, 0, 1) < (1, 1, 0)
1>0  3>2  5<99 -> (1, 3, 5) > (0, 2, 99)
0<1  1=1  1=1 -> (0, 1, 1) < (1, 1, 1)
1<2  2<3  3>1 -> (1, 2, 3) < (2, 3, 1)

```

And some examples of ambiguous tuples that are not valid comparisons (and so should not coexist in the same set)

```
1=1  1>0  1<2 -> (1, 1, 1) ? (1, 0, 2)
1>0  3=3  5<99 -> (1, 3, 5) ? (0, 3, 99)

```

Standard i/o rules apply, your output may be in any format so long as it's clear what the tuples are. This is , so the shortest answer in bytes wins.

## Test Cases

Some possible valid outputs.

```
1 -> (0, 0, 0)

3 -> (1, 2, 3)
     (2, 3, 1)
     (3, 1, 2)

5 -> (0, 3, 3)
     (1, 4, 1)
     (2, 0, 4)
     (3, 1, 2)
     (4, 2, 0)

```

Invalid outputs with the reason they are invalid

```
3 -> (0, 0, 0)  # this contains ambiguous tuple comparisons
     (-1, 0, 1)
     (-2, 0, 2)

5 -> (0, 3, 1)  # the first element here is less than 3 others but only greater than 1
     (1, 4, 3)
     (2, 0, 4)
     (3, 1, 2)
     (4, 2, 0)

```

# Answer
> 6 votes
# JavaScript (ES6), 50 bytes

-5 bytes by porting the formulas used in G B's answer, as suggested by G B.

```
n=>[...Array(i=n)].map(_=>[i+=n+~n/2,-i-(i%=n),i])

```

Try it online!

---

# JavaScript (ES6), 55 bytes

*-1 thanks to @KevinCruijssen*

Returns one perfect non-transitive set, built in a specific way.

```
n=>[...Array(i=n)].map(_=>[i,(i+~n/2)%n,(4*n-i-++i)%n])

```

Try it online!

### How?

The tuples are built as follows:

* First entry: \\$n\\$ to \\$2n-1\\$. It would be more obvious to use \\$0\\$ to \\$n-1\\$, but it's golfier that way.
* Second entry: \\$\lfloor n/2\rfloor\\$ to \\$n-1\\$, then \\$0\\$ to \\$\lfloor n/2\rfloor-1\\$.
* Third entry: \\$n-1\\$, \\$n-3\\$, ..., \\$0\\$, \\$n-2\\$, \\$n-4\\$, ..., \\$1\\$.

# Answer
> 3 votes
# Jelly, 12 bytes

```
rCm2ĖṠÞĖF€%o

```

A monadic Link that accepts an odd, positive integer and yields a list of triples.

**Try it online!**

Or see a check of the first 21
(checks that there are exactly \\$\frac{n-1}{2}\\$ others that are greater and exactly \\$\frac{n-1}{2}\\$ that are less for each triple in the result.).

### How?

```
rCm2ĖṠÞĖF€%o - Link: (odd, positive) integer, n
 C           - complement (n) -> 1-n
r            - (n) inclusive range (that) -> [n,n-1,n-2,...,1,0,-1,...,3-n,2-n,1-n]
  m2         - modulo two slice           -> [n,    n-2,...,1,  -1,...,3-n,    1-n]
    Ė        - enumerate -> [[1,n],[2,n-2],...,[(n+1)/2,1],[(n+3)/2,-1],...,[n-1,3-n],[n,1-n]]
      Þ      - sort by:
     Ṡ       -   sign (vectorises)
               ...rotates that list left by (n+1)/2 such that the [(n+3)/2,-1] entry is first
       Ė     - enumerate
        F€   - flatten each
          %  - modulo (n) (vectorises)
           o - logical OR (n) (vectorises) ...replaces zeros with n.

```

# Answer
> 3 votes
# Charcoal, 19 bytes

```
ＮθＩ﹪Ｅθ⟦ι⁺ι⊘⊕θ±⊗⊕ι⟧θ

```

Try it online! Link is to verbose version of code. Outputs the triples @JonathanAllan's answer does (except decremented because Charcoal is 0-indexed), but using a different approach to generating the triples. Explanation:

```
Ｎθ                  Input `n` as an integer
     θ              Input `n`
    Ｅ               Map over implicit range
      ⟦             List of
       ι            Current index
            θ       Input `n`
           ⊕        Incremented
          ⊘         Halved
        ⁺           Plus
         ι          Current index
                ι   Current index
               ⊕    Incremented
              ⊗     Doubled
             ±      Negated
                 ⟧  End of list
   ﹪                Vectorised modulo by
                  θ Input `n`
  Ｉ                 Cast to string
                    Implicitly print

```

# Answer
> 3 votes
# Ruby, ~~43 ...~~ 37 bytes

```
->n{(1..x=n).map{[x+=n/2,-x-x%=n,x]}}

```

Try it online!

### How?

I wish you didn't ask.

Just trial and error.

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

-5 bytes porting *@Neil*'s Charcoal answer (which in turn is based on *@JonathanAllan*'s Jelly answer \- so make sure to upvote both of them as well).

```
Lε<DI>;+y·()I%

```

Try it online or verify all odd inputs up to 15.

**Explanation:**

```
L           # Push a list in the range [1, (implicit) input-integer]
 ε          # Map over each integer `y`:
  <         #  Decrease the integer to make it 0-based
  D         #  Duplicate it
   I>       #  Push the input+1
     ;      #  Halve it
      +     #  Add it to the `y-1`
  y         #  Push `y` again
   ·        #  Double it
    (       #  Negate it
       )    #  Wrap all three values on the stack into a list
        I%  #  Modulo each by the input
            # (after which the list of triplets is output implicitly as result)

```

**Original 19 (18†) bytes brute-force approach:**

```
Ý3ãIã.ΔDδ.SOεD_«O}P

```

Very slow and will already time out for \\$n\geq5\\$..

Try it online. or verify 1 and 3...

† If we're allowed to output all possible results for a certain range (e.g. all valid results using integers in the range \\$\[0,n\]\\$), it could be 1 byte less by changing the  (find\_first) to `ʒ` (filter), although it'll then become even slower and already times out for \\$n=3\\$.. try it online.

**Explanation:**

```
Ý            # Push a list in the range [0, (implicit) input]
 3ã          # Get a list of all triplets using these values
   Iã        # Get all input-sized lists using these triplets
.Δ           # Find the first list of triplets which is truthy for:
  D          #  Duplicate the current list of triplets
   δ         #  Apply double-vectorized:
    .S       #   Vectorize-compare the triplets
             #   (e.g. [a,b,c] and [d,e,f] → [C(a,d),C(b,e),C(c,f)], where C(A,B) is a
             #   compare resulting in -1 if A<B; 0 if A==B; and 1 if A>B)
      O      #  Get the sum of each inner-most triplet comparison
       ε     #  Map over each inner list:
        D    #   Duplicate the list
         _   #   Check which values are equal to 0 (1 if 0; 0 otherwise)
          «  #   Merge the two lists together
           O #   Sum the list
       }P    #  After the map: take the product of this list of sums
             #  (only 1 is truthy in 05AB1E, so I basically check for each triplet-
             #  comparison [x,y,z] whether x+y+z+(x==0)+(y==0)+(z==0)==1 - meaning there
             #  is exactly one 0 and an equal amount of 1s and -1s)
             # (after which the result is output implicitly)

```

See here for a step-by-step output.

---
Tags: code-golf, math
---


title: Letters, Get Moving!

text:
# Question
Title: Letters, Get Moving!
Given a string you must move each letter (starting from the first letter) by its position in the alphabet. If you reach the end of the string you must wrap around. Non-letters don't need to be moved.

Example:

`Dog`

`D` is the fourth letter in the alphabet so we move it four spots to the right. After wrapping around, that changes the string to `oDg`. `o` is the 15th letter, (15 mod 3) = 0, so it does not move. `g` is the 7th letter - (7 mod 3) = 1, so the string becomes `goD`.

`hi*bye`

* `h` is the 8th letter, move it 8 spots - `hi*bye` =\> `i*hbye`
* `i` is the 9th letter, move it 9 spots - `i*hbye` =\> `*hbiye`
* `b` is the 2nd letter, move it 2 spots - `*hbiye` =\> `*hiybe`
* `y` is the 25th letter, move it 25 spots - `*hiybe` =\> `*hibye`
* `e` is the 5th letter, move it 5 spots - `*hibye` =\> `*hibey`

Non-letters don't need to be moved, but they still take up space.

* `cat` =\> `tca`
* `F.U.N` =\> `.F.NU`
* `mississippi` =\> `msiisppssii`

# Answer
## CJam, ~~44~~ ~~42~~ 40 bytes

```
qN+ee_{Xa/~\+XW=eu__el=!\'@-*m<Xa+}fXWf=

```

Output contains a trailing linefeed.

Test it here.

### Explanation

Instead of moving the letters through the string, I repeatedly remove a letter, rotate the string accordingly, and then reinsert the letter. There's one catch for doing this: we need to be able to distinguish the beginning of the string from the end of the string (which we can't after a simple rotation). That's why we insert a linefeed at the end as a guard (letter before the linefeed is the end of the string, letter after it is the beginning). The bonus is that this automatically returns the final string to the correct rotation where the linefeed actually *is* at the end of the string.

```
lN+     e# Read input and append a linefeed.
ee      e# Enumerate the array, so input "bob" would become [[0 'b] [1 'o] [2 'b] [3 N]]
        e# This is so that we can distinguish repeated occurrences of one letter.
_{      e# Duplicate. Then for each element X in the copy...
  Xa/   e# Split the enumerated string around X.
  ~     e# Dump the two halves onto the stack.
  \+    e# Concatenate them in reverse order. This is equivalent to rotating the current
        e# character to the front and then removing it.
  XW=   e# Get the character from X.
  eu    e# Convert to upper case.
  _     e# Duplicate.
  _el=! e# Check that convert to lower case changes the character (to ensure we have a
        e# letter).
  \'@-  e# Swap with the other upper-case copy and subtract '@, turning letters into 1 to
        e# 26 (and everything else into junk).
  *     e# Multiply with whether it's a letter or not to turn said junk into 0 (that means
        e# everything which is not a letter will be moved by 0 places).
  m<    e# Rotate the string to the left that many times.
  Xa+   e# Append X to the rotated string.
}fX
Wf=     e# Extract the character from each pair in the enumerated array.

```

To see why this ends up in the right position, consider the last iteration of the `hi*bye` example. After we've processed the `e`, the enumerated string is in this position:

```
[[4 'y] [6 N] [2 '*] [0 'h] [1 'i] [3 'b] [5 'e]]

```

First, we split around the linefeed and concatenate the parts in reverse order:

```
[[2 '*] [0 'h] [1 'i] [3 'b] [5 'e] [4 'y]]

```

The linefeed would now be either at the beginning or the end of this string. But since the linefeed is just a guard that *marks* the end of the string, this means that the characters are actually in the right order. Now the linefeed is not a letter, so that the array is not rotated at all. Thus, when we append the linefeed, it goes where it belongs, and everything is in the order we're looking for:

```
[[2 '*] [0 'h] [1 'i] [3 'b] [5 'e] [4 'y] [6 N]]

```

Some additional results if someone wants to compare longer test cases:

```
Hello, World!
,W oeHlo!lrld

Programming Puzzles & Code Golf
ago fgliPomomnrr elP& uC dezzsG

The quick brown fox jumps over the lazy dog
t eg chbi ko qfTounyzrj omw epx ueoahs rlvd

abcdefghijklmnopqrstuvwxyz
aqbrcdsetfguhivjwklxmnyozp

zyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyz

```

I like that last one. :)
> 6 votes

# Answer
# Ruby 125 ~~130 132 139~~ bytes

```
->q{a=q.chars.map{|c|[c,c=~/[a-z]/i&&c.ord%32]}
while i=a.index{|c,s|s}
c,s=a.delete_at i
a.insert (i+s)%q.size,[c]
end
a*''}

```

Online demo with tests: http://ideone.com/GYJm2u

The initial (ungolfed version): http://ideone.com/gTNvWY

*Edit:* Big thanks to manatwork for his suggestions!

*Edit 2*: fixed character count (I was initially counting CRLF line endings.)
> 4 votes

# Answer
# Python 3, ~~278~~ ~~275~~ ~~273~~ ~~270~~ ~~260~~ ~~258~~ ~~249~~ ~~248~~ ~~243~~ 238 bytes

I should really golf this down better, but here is my solution, with thanks to katenkyo for his help with the logic, and to Cyoce and Mego for their help with the golfing.

**Edit:** At last, I got it down to one comparison statement. WOO! (And yes, I could move that `z=-z` into `a,m=m,a` bit, but that doesn't save bytes and it muddled the code more than I thought was necessary)

**Edit:** Byte count was off.

```
def m(s):
 l=len(s);r=range(l);p=[[i,s[i]]for i in r]
 for i in r:
  if s[i].isalpha():
   a=p[i][0];p[i][0]=m=(a+ord(s[i])%32)%l;z=1
   if a>m:a,m=m,a;z=-z
   for j in r:p[j][0]-=z*(j!=i)*(a<=p[j][0]<=m)
 return''.join(dict(p).values())

```

**Ungolfed:**

```
def move(string):
 length = len(string)
 places = [[i,string[i]]for i in range(length)]
 for index in range(length):
  char = string[index]
  if char.isalpha():
   a = places[index][0]
   mov = (a + ord(char)%32) % length
   places[index][0] = mov
   for j in range(length):
    k = places[j][0]
    if a <= k <= mov and j!=index:
     places[j][0]-=1
    elif mov <= k <= a and j != index:
     places[j][0]+=1
 return''.join(dict(places).values())

```
> 3 votes

# Answer
# , 92 84 bytes

```
{~(g=.i.@#@[)([/:g(]+]-*@-)#@[|g+(={.)*1{])~&;/@([|.@;;/@,.)[:(26&|+52&>)Alpha_j_&i.

```

Attempt This Online!

*-8 thanks to rdm!*
> 3 votes

# Answer
# K (ngn/k), ~~46~~ 45 bytes

-1 byte from @Traws' improvement

```
{x{?[x^z;(#x)!y+x?z;z]}/[;a*27>a:96!_x].&=#x}

```

Try it online!

A bit complicated to unpack. Takes input as `x`.

* `&=#x` generate two copies of `0..count[input]` (e.g., `(0 1 2 3 4;0 1 2 3 4)`)
* `{...}/[;...].` set up a seeded-reduce, fixing the second (`y`) arg, and passing the pair of ranges as the first (`x`) and third (`z`) args. `x` represents the to-be-shuffled indices of the input, `y` the number of positions to shift each character in the input, and `z` the *initial* position of each character

+ `a*27>a:96!_x` determine the number of positions to shift each character in the input; non-letters are shifted `0` places, leaving them in the same position
    + `{?[x^z;(#x)!y+x?z;z]}/` set up a `?[x;indices;values]` splice. each iteration is run on the original input (`x`), a single number of positions to move (`y`), and a single initial position (`z`)
        - `x^z` remove the current item being shifted
        - `(#x)!y+x?z` determine where it should be after being moved (offset by where it is *now* (`x?z`), and with wrap-around `(#x)!`)
        - `z` re-insert the value/index at the correct position
* `{x{...}...}` index back into the original input, and (implicitly) return
> 2 votes

---
Tags: code-golf, string
---


title: Find the odd one out in a sequence

text:
# Question
Title: Find the odd one out in a sequence
**The Challenge:**

Consider the function `F(N) = 2^N + 1` where `N` is a positive integer less than `31`. The sequence defined by this function is:

```
3, 5, 9, 17, 33, 65, 129, 257, 513, 1025, 2049, 4097, 8193, 16385, 32769, 65537, 131073, 262145, 524289, 1048577, 2097153, 4194305, 8388609, 16777217, 33554433, 67108865, 134217729, 268435457, 536870913, 1073741825

```

An input will be generated as follows:

* Take 5 *contiguous* integers from the above sequence.
* Replace one of them with a different, positive integer (which may or may not be part of the above sequence).
* Optionally reorder the the 5 resulting numbers.

Given such a list of 5 integers, find the one that was swapped in and is therefore not part of the original 5 contiguous integers.

Example:

* Original sublist: `5, 9, 17, 33, 65`.
* Replace one: `5, 7, 17, 33, 65`.
* Reorder: `33, 17, 5, 7, 65`.

The expected output would be `7`.

The 5 values in the input will always be distinct and there will always be a unique solution. (For instance, you won't have to deal with inputs like `3, 9, 17, 33, 129` where either `3` or `129` might have been swapped in.)

**Test Cases:**

```
5,9,17,33,829
o/p: 829

9,5,17,829,33
o/p: 829

33, 17, 5, 7, 65
o/p: 7

5,9,177,33,65
o/p: 177

65,129,259,513,1025
o/p: 259

129,259,513,1025,65
o/p: 259

63,129,257,513,1025
o/p: 63

65,129,257,513,4097
o/p: 4097

5, 9, 2, 17, 33
o/p: 2

536870913, 67108865, 1073741825, 1, 268435457
o/p: 1

```

# Answer
# Jelly, 15 bytes

```
⁹R2*‘ṡ5ḟ@€µEÐfQ

```

**TryItOnline**
All test cases also at **TryItOnline**

Returns a list containing one list containing the odd one out.

How?

```
⁹R2*‘ṡ5ḟ@€µEÐfQ - Main link, a (list)
⁹               - literal 256 (saving a byte over literal 30)
 R              - range, [1,2,3,...]
  2*            - 2 ** x, [2,4,8,...]
    ‘           - increment, [3,5,9,...]
     ṡ5         - all contiguous slices of length 5
       ḟ@€      - filter with reversed arguments for each
          µ     - monadic chain separation
            Ðf  - filter on condition:
           E    - all equal (those previously filtered lists with only one value)
              Q - unique (there can be two, but both will have the same odd-one-out)

```
> 7 votes

# Answer
## JavaScript (ES6), 62 bytes

```
a=>a.find(n=>--n&--n|!n)||a.sort((a,b)=>a-b)[a[0]*16>a[3]?4:0]

```

Completely new algorithm, since as @edc65 pointed out the previous one was broken. Explanation: We first deal with the easy case by looking for a 2 or a number that is not one greater than a power of 2. If none was found then there are two possible cases, depending on whether the extra value was below or above the original run of five, so we check whether the smallest and second largest value belong to the same run of five and if so blame the largest value otherwise the smallest value.
> 5 votes

# Answer
## Racket 198 bytes

```
(λ(m)(let((l(for/list((i(range 1 31)))(+ 1(expt 2 i))))(r 1)(n(length m)))(for((i(-(length l)n)))(let
((o(for/list((j m)#:unless(member j(take(drop l i)n)))j)))(when(eq?(length o)1)(set! r o))))r))

```

Ungolfed version:

```
(define f
  (λ(m)
    (let ((l (for/list ((i (range 1 31)))
               (+ 1 (expt 2 i))))
          (res 1)
          (n (length m)))
      (for ((i (- (length l) n)))
        (let ((o (for/list ((j m)
                             #:unless (member j
                                             (take (drop l i) n)))
                    j)))
          (when (eq? (length o) 1)
            (set! res o))))
      res)))

```

Testing:

```
(f '(5 9 17 33 829))
(f '(9 5 17 829 33))
(f '(5 9 177 33 65))
(f '(65 129 259 513 1025))
(f '(129 259 513 1025 65))
(f '(63 129 257 513 1025))
(f '(65 129 257 513 4097))

```

Output:

```
'(829)
'(829)
'(177)
'(259)
'(259)
'(63)
'(4097)

```
> 4 votes

# Answer
# Python, 84 bytes

```
def f(a,i=0):s=set(a)-{2**j+1for j in range(i,i+5)};return len(s)<2and s or f(a,i+1)

```

All test cases are at **ideone**

For valid input returns a set containing only the odd-one-out.
For invalid input the recursion limit will be reached and an error will be thrown.
> 4 votes

# Answer
## Mathematica, 65 bytes

```
f[a___,x_,b___]/;NestList[2#-1&,a~Min~b/. 2->0,4]~SubsetQ~{a,b}=x

```

This defines a function `f` which should be called with 5 arguments, e.g.

```
f[5, 9, 17, 33, 829]

```

In principle the function can be called with any (non-zero) number of arguments, but you might get unexpected results...

I think this is the first time, that I managed to put the entire solution to a non-trivial challenge into the left-hand side of a `=`.

### Explanation

This solution really puts Mathematica's pattern matching capabilities to work for us. The basic feature we're using is that Mathematica can't just define simple functions like `f[x_] := (* some expression in x *)` but we can use arbitrarily complex patterns on the left-hand side, e.g. `f[{a_, b_}, x_?OddQ] := ...` would add a definition to `f` which is only used when it's called with a two-element list and an odd integer. Conveniently, we can already give names to elements arbitrarily far down the left-hand side expression (e.g. in the last example, we could immediately refer to the two list elements as `a` and `b`).

The pattern we're using in this challenge is `f[a___,x_,b___]`. Here `a___` and `b___` are *sequences* of zero or more arguments and `x` is a single argument. Since the right-hand side of the definition is simply `x`, what we want is some magic that ensures that `x` is used for the input we're searching for and `a___` and `b___` are simply wildcards that cover the remaining elements.

This is done by attaching a *condition* to the pattern with `/;`. The right-hand side of `/;` (everything up to the `=`) needs to return `True` for this pattern to match. The beauty is that Mathematica's pattern matcher will try every single assignment of `a`, `x` and `b` to the inputs for us, so the search for the correct element is done for us. This is essentially a declarative solution to the problem.

As for the condition itself:

```
NestList[2#-1&,a~Min~b/. 2->0,4]~SubsetQ~{a,b}

```

Notice that this doesn't depend on `x` at all. Instead, this condition depends only on the remaining four elements. This is another convenient feature of the pattern matching solution: due to the sequence patterns, `a` and `b` together contain all other inputs.

So this condition needs to check whether the remaining four elements are contiguous elements from our sequence with at most one gap. The basic idea for checking this is that we generate the next four elements from the minimum (via `x<sub>i+1</sub> = 2x<sub>i</sub> - 1`) and check whether the four elements are a subset of this. The only inputs where that can cause trouble is those that contain a `2`, because this also generates valid sequence elements, so we need to handle that separately.

Last part: let's go through the actual expression, because there's some more funny syntactic sugar here.

```
...a~Min~b...

```

This infix notation is short for `Min[a,b]`. But remember that `a` and `b` are sequences, so this actually expands to the four elements `Min[i1, i2, i3, i4]` and gives us the smallest remaining element in the input.

```
.../. 2->0

```

If this results in a 2, we replace it with a 0 (which will generate values which aren't in the sequence). The space is necessary because otherwise Mathematica parses the float literal `.2`.

```
NestList[...&,...,4]

```

We apply the unnamed function on the left 4 times to this value and collect the results in a list.

```
2#-1&

```

This simply multiplies its input by 2 and decrements it.

```
...~SubsetQ~{a,b}

```

And finally, we check that the list containing all elements from `a` and `b` is a subset of this.
> 4 votes

# Answer
# 05AB1E, ~~32~~ ~~30~~ ~~26~~ ~~24~~ 20 bytes

```
30Lo>Œ5ùv¹yvyK}Dgi`q

```

**Explanation**

```
30Lo>    # list containing the sequence [3 .. 1073741825]
Œ5ù      # all sequence sublists of length 5
v        # for each such list
 ¹yvyK}  # remove it's elements from input
 Dgi     # if the remaining list has length 1
    `q   # end the program and print the final list flattened

```

Try it online!
> 2 votes

# Answer
## Haskell, ~~66~~ 64 bytes

```
g x=[s|n<-[1..],[s]<-[filter(`notElem`[2^m+1|m<-[n..n+4]])x]]!!0

```

Usage example: `g [65,129,257,513,4097]` -\> `4097`.

Loops through all contiguous sublists of length 5 of `F(N)`, keeps the elements that are not in the input list `x` and pattern matches those of length 1 (-\> `[s]`).

Edit: @xnor saved two bytes by removing the upper bound of the outer loop. As a solution is guaranteed to exist, Haskell's laziness stops at the first number found.
> 2 votes

# Answer
## R, 97 bytes

This turned out to be more difficult than I thought. I'm sure this can be golfed significantly though.

```
m=match(x<-sort(scan()),2^(1:31)+1);l=diff(m);ifelse(NA%in%m,x[is.na(m)],x[ifelse(l[4]>1,5,l>1)])

```

### Ungolfed and explained

```
x<-sort(scan())                  # read input from stdin and sort, store as vector
m=match(x, 2^(1:31)+1)           # generate a vector of indices for which input matches the sequence
l=diff(m)                        # vector of the difference of indices (will only contain 4 elements)
ifelse(NA%in%m,                  # if m contains NA do:
       x[is.na(m)],              # return x where no match has been found, else:
       x[ifelse(l[4]>1,5,l>1)])  # return x by index where diff>1 unless it's the last object, then return x[5]

```

The `match()` function will return `NA` if the any element of the input vector is not in the sequence and consequently we can just find the index where `NA`exist in the input and return this: `x[is.na(m)]`

It gets a bit more complicated if input is part of the sequence but misplaced. Because input has been sorted, the distance between each pair of *indices* should be `1`. We can therefore find the misplaced element by investigating the `1st` difference of the matched indices `l=diff(m)` and select the index for which `l>1`. This would be just enough if it weren't for the fact that `l` contains `4` elements rather than `5`. This is only a problem if the last element in the sorted input is a member of the sequence BUT not a part of the subsequence (as in the final test case). Consequently, if the `4th` element `>1` fetch the `5th` entry in the sorted input else look for the index in the `4`-length vector: `x[ifelse(l[4]>1,5,l>1)]`
> 2 votes

# Answer
# Perl, ~~64~~ 59 bytes

Includes +2 for `-an`

Give input list on STDIN:

```
perl -M5.010 oddout.pl <<< "5 9 2 17 33"

```

`oddout.pl`:

```
#!/usr/bin/perl -an
@a=grep$_,@a{@F,map{2**$_+++1}($.++)x5}=@F while$#a;say@a

```

If you don't mind variable amount of space around the result this 58 byte verson works:

```
#!/usr/bin/perl -ap
$_=join$",@a{@F,map{2**$_+++1}($.++)x5}=@F while/\b +\b/

```

Both versions loop forever if the input has no solution.

This is very sick code, but I can't think of anything elegant...

The way I (ab)use `%a` is a new perlgolf trick as far as I know.
> 1 votes

# Answer
# PHP, ~~87~~ ~~76~~ 75 bytes

```
for(;count($b=array_diff($argv,$a?:[]))-2;)$a[$n%5]=1<<++$n|1;echo end($b);

```

run with `php -r '<code>' <value1> <value2> <value3> <value4> <value5>`
> 1 votes

# Answer
## Python 2, 73 bytes

```
s=set(input());i,=d={1}
while~-len(s-d):i*=2;d=d-{i/32+1}|{i+1}
print s-d

```

Iterates through sets `d` of five consecutive sequence elements until it finds one that contains all but one of the input elements, and then prints the difference, which is the output in a singleton set.

The sets `d` of five consecutive elements are built up from nothing by repeatedly adding a new element `i+1` and deleting any old element `i/32+1` that comes before the current window of 5. Here's what its progress looks like.

```
{1}
{3}
{3, 5}
{3, 5, 9}
{3, 5, 9, 17}
{3, 5, 9, 17, 33}
{5, 9, 17, 33, 65}
{9, 17, 33, 65, 129}
{17, 33, 65, 129, 257}
{33, 65, 129, 257, 513}

```

There's a stray 1 at the start from initialization, but it's harmless because it's immediately removed. The smaller sets as it builds up to 5 elements are also harmless.
> 1 votes

# Answer
# C#, 69 bytes

`int M(int[]a)=>a.Except(new int[30].Select((_,i)=>(1<<i+1)+1)).Sum();`
> 1 votes

# Answer
# Japt `-g`, ~~17~~ 15 bytes

Outputs a singleton array.

```
HÆÒ2pXÃã £kXÃl1

```

Try it

```
HÆÒ2pXÃã £kXÃl1     :Implicit input of array U
H                   :32
 Æ                  :Map each X in the range [0,32)
  Ò                 :  Negate the bitwise NOT of
   2pX              :  2 raised to the power of X
      Ã             :End map
       ã            :Sub-arrays
         £          :Map each X
          kX        :  Remove the elements in X from U
            Ã       :End map
             l1     :Filter elements of length 1
                    :Implicit output of first element

```
> 1 votes

# Answer
# Vyxal, 11 bytes

```
¨²›5l¨VF~₃h

```

Try it Online!
> 1 votes

# Answer
# Nibbles, 13 bytes (26 nibbles)

```
/+=~.;,30-_<5>$.@+^2$~,

```

Try it at nibbles.onrender.com

```
    .                       # each n of
      ,30                   # 1..30
     ;                      # (saving this range for later)
                            # using function:
         -_                 #   get difference between input and
           <5               #   first 5 elements
             >$             #   after dropping n elements from
                @           #   1..30
               .            #   each
                  ^2$       #   used as an exponent of 2
                 +          #   added to
                     ~      #   1
  =~                        # now group & sort results by
                       ,    #   length
 +                          # flatten this list of lists
/                           # and fold over this returning the leftmost element
                            # (which is the single element in the smallest-length list)

```
> 1 votes

# Answer
# Java 7,85 bytes

```
int f(int[]a,int l){int i=1;for(;i<l;)if(a[i++-1]*2-1!=a[i])return a[i];return a[0];}

```

# Ungolfed

```
int f(int[]a,int l){
    int i=1;
    for(;i<l;)
    if(a[i++-1]*2-1!=a[i])
    return a[i];
   return a[0];

}

```
> 0 votes

# Answer
# PHP, 76 Bytes

implemented Titus idea with the mod 5

```
<?for(;count($x=array_diff($_GET[a],$r))-1;$r[++$i%5]=2**$i+1);echo end($x);

```

126 Bytes before

```
<?for(;$x=array_diff($_GET[a],array_map(function($z){return 2**$z+1;},range(++$i,$i+4)));)if(count($x)<2){echo end($x);break;}

```
> 0 votes

# Answer
# Pyth, 18 bytes

```
hhlD-LQ.:mh^2dSCd5

```

Form the sequence, take sublists of length 5, Remove each sublist from Q, take the shortest result, output its only element.
> 0 votes

# Answer
# Kotlin, 55 bytes

`fun f(a:IntArray)=a.find{it-1 !in(1..30).map{1 shl it}}`
> 0 votes

# Answer
# Ruby, 70 bytes

```
->a{(1..a.max).map{2**_1+1}.each_cons(5).map{b=a-_1
break b if !b[1]}}

```

Attempt This Online!
> 0 votes

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