title: Repeat Repetitive Repetitions

text:
# Question
Title: Repeat Repetitive Repetitions
Your challenge is to generate this string:

```
[encoded data, 15558 characters]

```

or split into lines with length of 80:

```
[encoded data, 15558 characters]
```

## Notes:

* You may return an array of the characters (or digits) of the string
* You may use characters other than 0 and 1 if you want.
* You can have other characters in the output, as long as, if filtered for your two chosen characters, would result in this pattern.
* This string is generatable in way better ways than just hardcoding the whole string. A big part of the challenge is to find the shortest way to generate it. I've made a 16-byte SOGL answer that *should* be a language-agnostic algorithm (an old SOGL version specific 15-byte answer is what inspired the challenge), trough I'm not gonna post it (until someone finds that algorithm) to make the challenge more interesting for others.
* This is , so the shortest answer (per language) wins!

### Snippet to check the validness of an answer:

```
function check() {
  if (chr0.value == "") chr0.value = "0"
  if (chr1.value == "") chr1.value = "1"
  inp.value = inp.value.replace(new RegExp("[^"+JSON.stringify(chr0.value+chr1.value)+"]", "g"), "")
  if (inp.value == correct)
    output.innerHTML = "Matches"
  else
    output.innerHTML = "Doesn't match"
}
correct = "[encoded data, 15558 characters]"
```

```
<input id="inp" placeholder="input your result here"/><br>
<input id="chr0" placeholder="character for 0 (def=0)"/>
<input id="chr1" placeholder="character for 1 (def=1)"/><br>
<button id="chk" onclick="check()">check</button>
<div id=output></div>
```

# Answer
# Japt, ~~35~~ ~~33~~ ~~29~~ ~~26~~ ~~25~~ 24 bytes

```
'1
#˜5s £=r1,26¤²²sX
s#ž

```

Try it online!

### Explanation

```
'1   First line: Set variable U to this value.
'1   Yield the string "1". (This part gets simpler every time I golf this answer...)

1525s £=r1,26¤²²sX   Second line: Set variable V to this value (though that's not important).
1525s                Yield the string "1525".
      £              For each char X in this string:
           26¤         Yield the binary representation of 26. "11010"
              ²²       Double it twice.                       "11010110101101011010"
                sX     Slice off the first X chars. This gives "1010110101101011010",
                       "110101101011010", "010110101101011010", and "110101101011010".
       =               Set U to
        r1,              U with each instance of 1 replaced with the string calculated above.

s158   Last line: output the result of this line.
s158   Take U and slice off the first 158 characters.

```

Here's how I got this. Start with the original sequence:

```
01101011010110100110101101011010110101101011010011010110101101001101011010110101101011...

```

After some messing around, I realized that the sequence consisted entirely of copies of `0` and `11010`. Replacing each instance of `11010` with `2` gave this:

```
02220222222022202222220222022222202220002220222222022202222220222022222202220002220222...

```

Oh hey, now it's entirely made of `0` and `222`. Let's change each `222` to a single `2`:

```
02022020220202202000202202022020220200020220202202022020020220202202022020002022020220...

```

This sequence looks an awful lot like the original. There seems to be a lot of `22020`s in this, so I replaced each with `3` and got this:

```
02033300203330020333020333002033300203330203330020333000203330203330020333002033302033...

```

Now each instance of `3` is contained in a `020333`. Replacing each of these again with a single `3` gives this:

```
30303303033030033030330303303003303033030330303303033030330300330303303033030033030330...

```

...and we're back to the original pattern again. One more time, replacing `33030` with `4`:

```
30304404440444444044404444440444044444404440

```

Uh-oh, there's some stray chars at the beginning. We can fix this by adding an extra `3` at the beginning before condensing (this is where the 158 extra chars at the end comes from). Then we condense each run of 3 `4`s into a single `4`, as before:

```
4040440404404044040

```

Aaaaand yet again, we're back to the original pattern. One last time, let's condense copies of `44040` to `5`:

```
4040555

```

Hopefully this final step isn't too hard to understand. It's like the step where we compressed the `020333`s into `3`s, except this time, we're compressing `4040555`s into `5`s:

```
5

```

And there you have the fully compressed string. The code simply reverses the repeated compression to get back the original string. Since all compression iterations were nearly identical, it doesn't take much to reorganize the string properly.
> 35 votes

# Answer
## JavaScript (ES6), 130 bytes

Multicolor nonlinear pulse compression by consecutive optical parametric amplification in quasi-phase matched structures.

<sup>OK, not quite. Just substitutions.</sup>

```
f=(n=0,s='pqh0f9bc9bc9bc900')=>n<20?f(n+1,s.split((n+9).toString(36)).join('cb0dgfgnjkkoppo0qs10'[n]+'adcdef0hi0klmnqpqrs1'[n])):s

```

### Demo

```
f=(n=0,s='pqh0f9bc9bc9bc900')=>n<20?f(n+1,s.split((n+9).toString(36)).join('cb0dgfgnjkkoppo0qs10'[n]+'adcdef0hi0klmnqpqrs1'[n])):s

o.innerHTML = f()
```

```
<pre id=o></pre>
```

### How?

This is definitely not the best way to compress this string, but I thought I'd post it anyway since I went to the trouble of optimizing it (slightly) with a recursive function.

We start with the string `s="pqh0f9bc9bc9bc900"` and successively apply the following 20 substitutions:

```
 9  | a  | b  | c  | d  | e  | f  | g  | h  | i  | j  | k  | l  | m  | n  | o  | p  | q  | r  | s
----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----
 ca | bd | 0c | dd | ge | ff | g0 | nh | ji | k0 | kk | ol | pm | pn | oq | 0p | qq | sr | 1s | 01

```

For instance, a *"9"* will expand to *"ca"*, *"cbd"*, *"c0cd"*, *"dd0ddd"*, ..., and ultimately a 2381-character string of 0's and 1's.
> 14 votes

# Answer
# Mathematica, 128 bytes

```
Fold[StringReplace,"AAAY0PY0",{{"A"->"Y0PY0PYP"},{"Y"->"P0P0PP0P0PP0P0"},{"P"->"QQQXXX00"},{"Q"->"XXX0XXXXXX0"},{"X"->"01101"}}]

```

Try it online!
> 6 votes

# Answer
# Retina, ~~69~~ ~~66~~ 65 bytes

Port of @ETHproduction's JavaScript (ES6) answer: Try it online! N.B. Somewhat slow.

```

1¶1010::010::
{`1(?=.*¶(\d*):)
$1ZZZ
Z
11010
}1`\d*:

^.{158}|¶

```

A port of @Jenny\_mathy's Mathematica answer was ~~82~~ 66 bytes: Try it online!

```

AAAY0PY0
A
Y0PY0PYP
Y
ZPZPZ
Z
P0P0
P
QQQR00
Q
R0RR0
R
XXX
X
01101

```

A port of @ETHproduction's Japt explanation was 69 bytes: Try it online!

```

5454545
5
4040
4
444
4
33030
3
020333
3
22020
2
222
2
11010
^.{158}

```

A port of @ETHproduction's previous Japt explanation was also 69 bytes: Try it online!

```

___101
_
10101
1
111
1
11010
1
___100
_
10110
1
111
1
11010
^.{157}

```

A port of @RickHitchcock's JavaScript answer was 74 bytes: Try it online!

```

ifififhg0
i
hhg
h
g0f
g
f0f0ff0f0ff0f0
f
e0e0e0ddd00
e
ddd0dddddd
d
01101

```

A port of @Arnauld's JavaScript answer was 85 bytes: Try it online!

```

pqh0g09bc9bc9bc900
9
cbd
b
0c
c
dd
d
gg0g0
g
nh
h
kkk0
k
0pppn
n
0pq
p
qq
q
s1s
s
01

```
> 6 votes

# Answer
## JavaScript (ES6), ~~85~~ 80 bytes

```
[j="1",5,2,5].map(x=>j=j.replace(/1/g,"11010".repeat(4).slice(x)))&&j.slice(158)

```

Somewhat of a port of my Japt answer. An explanation of the pattern can be found over there.

### Test snippet

```
var q = [j="1",5,2,5].map(x=>j=j.replace(/1/g,"11010".repeat(4).slice(x)))&&j.slice(158);

var o = "[encoded data, 15558 characters]";

console.log(q === o);
```
> 6 votes

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

```
⁽.⁷Dð26Bẋ4ṫȧ€Ẏð/ṫ159

```

Try it online!

-3 thanks to Jonathan Allan.

(Somewhat) port of ETHproductions's excellent Japt answer.

Still not efficient as dzaima's (old SOGL version)!

This returns an array of digits.
> 6 votes

# Answer
# JavaScript (ES6), ~~158~~ ~~143~~ 139 bytes

*(Saved some bytes thanks to @DanTheMan.)*

```
'ifififhg0'[r='replace'](/i/g,'hhg')[r](/h/g,'g0f')[r](/g/g,'f0f0ff0f0ff0f0')[r](/f/g,'e0e0e0ddd00')[r](/e/g,'ddd0dddddd')[r](/d/g,'01101')

```

```
console.log('ifififhg0'[r='replace'](/i/g,'hhg')[r](/h/g,'g0f')[r](/g/g,'f0f0ff0f0ff0f0')[r](/f/g,'e0e0e0ddd00')[r](/e/g,'ddd0dddddd')[r](/d/g,'01101'));
```
> 3 votes

# Answer
# 05AB1E, 20 bytes

```
1Ž5ûv1₂b4×y.$.:]Ƶv.$

```

Try it online!

Port of ETHProductions's JAPT answer.
> 2 votes

# Answer
# K (ngn/k), 86 bytes

```
@[&15558;+\(,/(,/(,/(1 5,,/(1_,/(11#5 6 6),\:5 5),\:4 5),\:9#3 2 3),\:2 2),\:1 2);:;1]

```

Try it online!
> 1 votes

---
Tags: code-golf, kolmogorov-complexity
---


title: Make a Bowl of Alphabet Soup

text:
# Question
Title: Make a Bowl of Alphabet Soup
This is what we'll call a bowl of alphabet soup - a roughly circular ascii-art shape with the 26 uppercase English letters (A-Z) arranged clockwise to form the perimeter:

```
   XYZABC
 VW      DE
U          F
T          G
S          H
 RQ      JI
   PONMLK

```

Write a program that takes in a single letter character, A-Z, and outputs that same bowl of alphabet soup "rotated", so to speak, so the input letter appears where the `A` does in the example above and the rest of the alphabet cycles fully around clockwise.

So the output for input `A` would be that same original bowl of alphabet soup.

And the output for input `B` would be this one:

```
   YZABCD
 WX      EF
V          G
U          H
T          I
 SR      KJ
   QPONML

```

Likewise the output for `H` would be:

```
   EFGHIJ
 CD      KL
B          M
A          N
Z          O
 YX      QP
   WVUTSR

```

Or for `Z`:

```
   WXYZAB
 UV      CD
T          E
S          F
R          G
 QP      IH
   ONMLKJ

```

This needs to work for all 26 letters, A through Z.

### Details:

* You can assume the only input will be a single letter, A through Z.
* If convenient you may use lowercase a-z for input and/or output, you can even mix and match lower and uppercase.
* The alphabet order must cycle clockwise, not counter-clockwise.
* You must use spaces, not something else, to indent and fill the soup bowl.
* There may be leading or trailing newlines or spaces in the output as long as the soup bowl is arranged properly.
* Note that the bowl shape is 12 characters wide by 7 tall to make it appear roughly circular as text. Your bowls need to be the same shape.

**This is code golf so the shortest code wins!**

# Answer
> 24 votes
# 05AB1E, 21 bytes

Defines a program \\$f : \color{purple}{\texttt{AlphabeticChar}} \rightarrow \color{purple}{\texttt{String}}\\$

### Code:

```
2AA¹k._•1ëª»*Ć,ãiDΣ•Λ

```

Try it online!

### Breakdown:

```
2AA¹k._•1ëª»*Ć,ãiDΣ•Λ

2                       # <length>
 AA¹k._                 # <filler>
       •1ëª»*Ć,ãiDΣ•    # <pattern>
                    Λ   # Invoke the canvas function.

```

### Explanation:

The **canvas** (`Λ`) in this particular context works as a function with the following signature:

$$ \mathsf{\Lambda} : \left(\texttt{length}: \color{purple}{\texttt{Nat}},\ \texttt{filler}: \color{purple}{\texttt{String}},\ \texttt{pattern}: \color{purple}{\texttt{Nat}}\right) \rightarrow \color{purple}{\texttt{String}} $$

The \\$\texttt{pattern}\\$ parameter is in this situation a number defining the directions. In the code, this number is represented as `•1ëª»*Ć,ãiDΣ•`, which is a compressed version of the big number \\$2232344565666667670012122\\$. Directions are denoted in the following manner:

$$ \begin{array}{l} 7 & & 0 & & 1 \\ & \nwarrow & \uparrow & \nearrow & \\ 6 & \leftarrow & \bullet & \rightarrow & 2 \\ & \swarrow & \downarrow & \searrow & \\ 5 & & 4 & & 3 \end{array} $$

This means that the big number represents the following pattern of directions:

$$ \[\rightarrow, \rightarrow, \searrow, \rightarrow, \searrow, \downarrow, \downarrow, \swarrow, \leftarrow, \swarrow, \leftarrow, \leftarrow, \leftarrow, \leftarrow, \leftarrow, \nwarrow, \leftarrow, \nwarrow, \uparrow, \uparrow, \nearrow, \rightarrow, \nearrow, \rightarrow, \rightarrow\] $$

With this signature context, the canvas iterates through the \\$\texttt{pattern}\\$ list and writes \\$\texttt{length}\\$ characters from the \\$\texttt{filler}\\$ in the current direction.

The \\$\texttt{length}\\$ is specified in the code as \\$2\\$ (at the beginning of the code). For the \\$\texttt{filler}\\$, we need a rotated version of the alphabet such that it starts with the given input. That is done with the following code (try it here):

```
**AA¹k._**

 A¹k       # Find the ***<index>*** of the given input character in the alphabet
A   ._     # Rotate the alphabet to the left ***<index>*** times.

```

In pseudocode, this would be executed by the canvas function:

\\$ \begin{array}{l} 1. & \text{Write } \color{blue}{\texttt{ab}} \text{ in the direction} \rightarrow \\ 2. & \text{Write } \color{blue}{\texttt{bc}} \text{ in the direction} \rightarrow \\ 3. & \text{Write } \color{blue}{\texttt{cd}} \text{ in the direction} \searrow \\ 4. & \text{Write } \color{blue}{\texttt{de}} \text{ in the direction} \rightarrow \\ 5. & \text{Write } \color{blue}{\texttt{ef}} \text{ in the direction} \searrow \\ 6. & \text{Write } \color{blue}{\texttt{fg}} \text{ in the direction} \downarrow \\ \dots \end{array} \\$

Lastly, you can see that the filler argument is 'rotated' \\$\texttt{length} - 1\\$ times to the right, meaning that the canvas would iterate through the following (cycled and therefore infinite) list:

$$ \[\color{blue}{\texttt{ab}}, \color{blue}{\texttt{bc}}, \color{blue}{\texttt{cd}}, \color{blue}{\texttt{de}}, \color{blue}{\texttt{ef}}, \color{blue}{\texttt{fg}}, \color{blue}{\texttt{gh}}, \color{blue}{\texttt{hi}}, \color{blue}{\texttt{ij}}, \color{blue}{\texttt{jk}}, ... $$

Which results in the desired alphabet soup ascii-art shape.

# Answer
> 11 votes
# Perl 6, 100 bytes

```
{"2XYZABC
 VW5DE
U9F
T9G
S9H
 RQ5JI
2PONMLK".trans(/\S/=>{(try ' 'x$/+1)||chr ($/.ord+.ord)%26+65})}

```

Try it online!

Replaces all letters in the string with their shifted counterparts, while replacing digits with the number of spaces they represent plus one.

### Explanation

```
{                                                            }# Anonymous code block
 "...".trans(/\S/=>{                                       }) # Translate non-whitespace
                    (try ' 'x$/+1)      # If digits, the amount of spaces plus one
                                  ||chr ($/.ord+.ord)%26+64  # Else the shifted letter

```

# Answer
> 9 votes
# MATL, 49 bytes

```
7I8*32tvB[1b]&Zvc2Y2j7+_YSy&f7-w4-_Z;YPE\,&S])yg(

```

What a mess. But it was fun writing. There's even an arctangent involved.

**Try it online!**

### Explanation

The code

```
7I8*32tvB

```

creates an array of numbers and converts them to binary. This gives the zero-one matrix

```
0 0 0 1 1 1
0 1 1 0 0 0
1 0 0 0 0 0
1 0 0 0 0 0

```

which is the top left quadrant of a matrix specfying the positions of the letters.

```
[1b]&Zv

```

reflects that quadrant vertically without repeating the last row, and horizontally repeating the last column to produce the full matrix:

```
0 0 0 1 1 1 1 1 1 0 0 0
0 1 1 0 0 0 0 0 0 1 1 0
1 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 1
0 1 1 0 0 0 0 0 0 1 1 0
0 0 0 1 1 1 1 1 1 0 0 0

```

We now have a mask with the positions. The code

```
c

```

converts this to char, because the final result will be a char matrix. Character 0 is displayed as space, and the nonzero entries will be written with the appropriate letters.

```
2Y2

```

pushes the string `'abc···xyz'`, which contains the 26 letters. This string needs to be circularly shifted as per the input. To do that,

```
j7+_YS

```

reads the input letter, adds 7 to its ASCII code, and negates the result. For input `'a'` this gives −104, which is a multiple of 26, so circularly shifting by this amount will do nothing. If the input is `b` this gives −105, which shifts the string 1 step to the left to produce `'bcd···yza'`; etc.

The next step is to define the order in which the shifted string will be written into the nonzero entries of the matrix. To this end,

```
y&f

```

creates a copy of the matrix and pushes two vectors containing the 1-based row and column positions of the nonzeros. Then

```
7-w4-_

```

subtracts 7 from the latter, brings the former to top, substracts 4 from it, and negates it. The 7 and 4 specify an origin of coordinates, so that the angles of the position vectors of the nonzero entries with respect to that origin define the desired order.

```
Z;YPE\

```

computes the two-argument arctangent modulo 2\*pi to produce those angles. Now the smallest angle, which is 0, corresponds to the entry where the first letter should go, and the rest advance counter-clockwise.

```
,&S])

```

rearranges the letters in the string according to those angles, so that when the letters are written into the nonzero entries of the matrix in column-major order (down, then across) the result will be correct. This is done by

```
yg(

```

For example, if the input is `'a'` the string was not circularly shifted:

```
abcdefghijklmnopqrstuvwxyz

```

The rearranging as per the angles transforms this into

```
utsvrwqxpyoznamblckdjeifgh

```

so that `'u'` will correctly go to the first (in column-major order) nonzero entry, which is (3,1) in matrix notation; `'t'` will go to (4,1), `'s'` to (5,1); `'v'` to (2,2) etc:

```
   ······
 v·      ··
u          ·
t          ·
s          ·
 ··      ··
   ······

```

# Answer
> 9 votes
# Ruby, 107 bytes

```
->n{a=(0..6).map{' '*11}
(?A..?Z).map{|i|j,k=(1i**((i.ord-n.ord-6)/6.5)).rect;a[3.5*k+=1][5.2*j+6]=i}
a*$/}

```

Try it online!

Improved syntax `"i".to_c` -\> `1i` (Suggested by Jordan)

Changed coordinate system so 0 degrees is at right instead of top. This enables `0.5` -\> `6`

Adjusted multipliers of `j` and `k` for shortness

Rather than print output `puts a`, concatenate array elements and return a string `a*$/`

# Ruby, 119 bytes

```
->n{a=(0..6).map{' '*11}
(?A..?Z).map{|i|j,k=("i".to_c**((i.ord-n.ord+0.5)/6.5)).rect;a[3.5-j*3.3][6+k*5.17]=i}
puts a}

```

Uses a complex number raised to a power to map to an ellipse. A complete turn is 26, so each quadrant is 6.5.

This approach relies on the required output resembling an ellipse sufficiently that a valid mapping can be achieved.

Try it online!

# Answer
> 8 votes
# Charcoal, 33 bytes

```
ＧＨ→→↘→↘↓↓77←←←←↖←↖↑↑↗→↗→→²✂⁺αα⌕αＳ

```

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

```
ＧＨ

```

Trace a path.

```
→→↘→↘↓↓77←←←←↖←↖↑↑↗→↗→→

```

Outline the bowl. Each `7` expands to `↙←`.

```
²

```

Move one character at a time (this API overlaps each line's ends with the next).

```
✂⁺αα⌕αＳ

```

Draw using the doubled alphabet, but starting at the position of the input character.

# Answer
> 7 votes
# Python 2, 129 bytes

```
lambda x:''.join((i,chr((ord(x)+ord(i))%26+65),' '*5)[ord(i)/46]for i in'''   XYZABC
 VW] DE
U]]F
T]]G
S]]H
 RQ] JI
   PONMLK''')

```

Try it online!

# Answer
> 7 votes
# , 139 122 bytes

-17 bytes thanks to Giuseppe

```
u=utf8ToInt;`*`=rep;o=c(' '*12,'
')*7;o[u("  &3@LKWVUTSRDC5(")]=LETTERS[(13:38+u(scan(,'')))%%26+1];cat(o,sep='')

```

Explanation:

```
o=rep(c(rep(' ',12),'
'),7)

```

Builds an empty box of spaces

```
u(" &3@LKWVUTSRDC5(")

```

is a set of indices for letter positions corresponding to:

```
c(7:9,23,24,38,51,64,76,75,87:82,68,67,53,40,27,15,16,4:6)

```

TIO

# Answer
> 6 votes
# JavaScript (Node.js),  ~~121~~  119 bytes

*Saved 2 bytes thanks to @tsh*

```
c=>`2XYZABC
0VW5DE
U9F
T9G
S9H
0RQ5JI
2PONMLK`.replace(/./g,x=>''.padEnd(+x+1)||(B=Buffer)([65+([a,b]=B(c+x),a+b)%26]))

```

Try it online!

## How?

This code abuses `Buffer` to extract the ASCII codes of the template letter \\$x\\$ and input letter \\$c\\$ and convert them back into the target letter.

### Example with \\$c=\\$`"H"` and \\$x=\\$`"B"`

```
// extracting the ASCII codes
Buffer(c + x) → Buffer("HB") → <Buffer 48 42>

// assigning them to variables
[a, b] = Buffer(c + x) → a = 0x48 (72) and b = 0x42 (66)

// computing the ASCII code of the target letter
65 + ((a + b) % 26) → 65 + (138 % 26) → 65 + 8 → 73

// turning it back into a character
Buffer([73]) → <Buffer 49> → implicitly coerced to "I" by replace()

```

# Answer
> 4 votes
# APL+WIN, 72 bytes

Prompts for character

```
m←7 12⍴' '⋄n←(7⍴2)⊤v,⌽v←(⍳3)/28 34 65⋄((,n)/,m)←(22+s⍳⎕)⌽s←⎕av[65+⍳26]⋄m

```

Try it online!Coutesy of Dyalog Classic

# Answer
> 4 votes
# , 218 197 bytes

-21 bytes thanks to Giuseppe

```
function(t,l=letters,`*`=rep,s=" ",n="
",`~`=`[`,r=c(l~l>=t,l))cat(s*3,r~24:26,r~1:3,n,s,r~22:23,q<-s*6,r~4:5,n,r~21,u<-s*10,r~6,n,r~20,u,r~7,n,r~19,u,r~8,n,s,r~17:18,q,r~10:9,n,s*3,r~16:11,sep='')

```

Try it online!

Ungolfed:

```
alphasoup <- function(startlet){
  startnum <- which(l == startlet)
  rotatedletters <- c(letters[startnum:26], letters[1:(startnum -1)])[1:26]
  cat('   ',rotatedletters[24:26],rotatedletters[1:3], '\n ',
      rotatedletters[22:23], s6 <- '      ', rotatedletters[4:5], '\n',
      rotatedletters[21], s10 <- rep(' ', 10), rotatedletters[6], '\n',
      rotatedletters[20], s10, rotatedletters[7], '\n',
      rotatedletters[19], s10, rotatedletters[8], '\n ',
      rotatedletters[17:18], s6, rotatedletters[10:9], '\n   ',
      rotatedletters[16:11],
      sep = '')
}

```

Created rotated letter vector and uses `cat` to fill out rim of bowl with that vector.

# Answer
> 4 votes
# Java 11, 134 bytes

```
c->"2XYZABC_0VW5DE_U9F_T9G_S9H_0RQ5JI_2PONMLK".chars().forEach(i->System.out.print(i<59?" ".repeat(i-47):(char)(i>90?10:(c+i)%26+65)))

```

Try it online.

**136 bytes version** with potential to be golfed?

```
c->"2XYZABC_0VW5DE_U9F_T9G_S9H_0RQ5JI_2PONMLK".chars().forEach(i->System.out.printf("%"+(i<59?i-47:"")+"c",i>90?10:i<59?32:(c+i)%26+65))

```

Try it online.

**Explanation (of the first answer)**

```
c->                          // Method with character parameter and no return-type
  "2XYZABC_0VW5DE_U9F_T9G_S9H_0RQ5JI_2PONMLK"
                             //  Template-String
    .chars().forEach(i->     //  Loop over the unicode values of its characters:
    System.out.print(        //   Print:
     i<59?                   //    If the value is below 59 (so a digit character):
      " ".repeat(i-47)       //     Repeat a space that digit + 1 amount of times
     :(char)(i>90?           //    Else-if the value is above 90 (an underscore character):
              10             //     Print a newline
             :               //    Else:
              (c+i)          //     Add the current value and the input together
                   %26       //     Take modulo-26 of it to get the index in the alphabet
                      +65))) //     And add 65 to make it an uppercase letter

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 258 bytes

```
(t[x_]:=Table[" ",x];w=RotateRight[Alphabet[],4-LetterNumber@#];j=Join;a[x_,y_]:=j[{w[[x]]},t@10,{w[[y]]}];b[m_,n_]:=j[t@1,w[[m;;m+1]],t@6,w[[n;;n+1]],t@1];""<>#&/@{j[t@3,w[[1;;6]]],b[25,7],a[24,9],a[23,10],a[22,11],Reverse@b[12,20],j[t@3,w[[19;;14;;-1]]]})&

```

Try it online!

# Answer
> 2 votes
# TSQL query, 238 bytes

```
DECLARE @y char='G'

,@ char(91)=3;WITH C as(SELECT'5585877636333330301125255'z,8a,ascii(@y)x
UNION ALL
SELECT stuff(z,1,1,''),a+left(z,1)/3*13+left(z,1)%3-14,(x+14)%26+65FROM
C WHERE''<z)SELECT
@=stuff(stuff(@,a,1,char(x)),1+a/13*13,1,char(13))FROM
C PRINT @

```

The test link for this answer broke the line breaks and excluded the spaces. I have replaced the spaces with period and replaced char(13) with char(13)+char(10) in order to show a readable result.

**Try it online**

Ungolfed:

```
DECLARE @y char='G'

-- @ is the string being printed last.
-- @ is populated with 3 to save a byte
-- the number 3 gets replaced later
-- (this could have been any 1 digit value),
-- @ is automatically filled with spaces, because
-- it is declared as a char(x) and assigned a value
,@ char(91)=3;
-- recursive query
WITH C as
(
-- z string containing digits for the direction of next letter
-- z should not contain 4 because it will point to same position.
-- values in z 0,1,2,3,4,5,6,7,8 can logally convert to
-- (-1,-1),(-1,0),(-1,1),(0,-1),(0,0),(0,1),(1,-1),(1,0),(1,1)
-- a is the starting position
  SELECT'5585877636333330301125255'z,8a,ascii(@y)x
  UNION ALL
-- stuff remove first character from the z string
-- a calculate next position of the next letter
-- x cycle the input letter
  SELECT stuff(z,1,1,''),a+left(z,1)/3*13+left(z,1)%3-14,(x+14)%26+65
-- repeat recursive until long string is empty
  FROM C
  WHERE''<z
)
SELECT
-- 1st stuff replace the character to created the start of a
--   logical line in the string @ this is where 3 gets overwritten
-- 2nd stuff replaces a character(space if coded correct)
--  with the letter at the calculated position.
  @=stuff(stuff(@,a,1,char(x)),1+a/13*13,1,char(13))
FROM C

PRINT @

```

# Answer
> 2 votes
# Kotlin, ~~148~~ ~~146~~ 145 bytes

Removed extra parentheses for -2
Replaced raw string for -1

```
{l:Char->"2XYZABC 0VW5DE U9F T9G S9H 0RQ5JI 2PONMLK".map{c->if(c>'@')((c-'A'+(l-'A'))%26+65).toChar()
else if(c>' ')" ".repeat(c-'/')
else '\n'}}

```

Try it online!

# Answer
> 2 votes
## Haskell, 127 bytes

```
("cXYZABC aVWfDE UjF TjG SjH aRQfJI cPONMLK">>=).(?)
t?c|c>'Z'=' '<$['a'..c]|c<'!'="\n"|t<'B'=[c]|c>'Y'=t?'@'|1<2=pred t?succ c

```

Try it online!

Each character in the encoded string is decoded by function `?` into a string:

```
t?c                             -- 't' is the starting char,
                                -- 'c' the char from the encoded string
   |c>'Z'=' '<$['a'..c]         -- if 'c' is a lowercase letter, return some spaces
                                -- 'a': one, 'b': two, etc
   |c<'!'="\n"                  -- if 'c' is a space, return a newline
   |t<'B'=[c]                   -- if 't' is the letter A, return 'c'
   |c>'Y'=t?'@'                 -- wrap around Z
   |1<2=pred t?succ c           -- else the result is the same as starting one letter
                                -- earlier (pred t) but looking at the successor of 'c'

```

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), ~~126~~ 118 bytes

```
n=>$@"   XYZABC
 VW{"",6}DE
U {"",9}F
T {"",9}G
S {"",9}H
 RQ{"",6}JI
   PONMLK".Select(b=>b<65?b:(char)((b+n)%26+65))

```

Saved 8 bytes thanks to @someone. Yes, that's actually his username.

Try it online!

# Answer
> 2 votes
# C(GCC) ~~286~~ 270 bytes

-12 bytes ceilingcat

Not exactly the shortest golf, but it works

```
#define r(a)(a+c)%26+65
#define R(a)for(i=10;i;a[--i]>32?a[i]=r(a[i]):0);
i;f(c){char T[]="   XYZABC\n",E[]="VW      DE\n",F[]="RQ      JI\n",B[]="   PONMLK";R(T)R(E)R(F)R(B)printf("%s %s%c%*c\n%c%*c\n%c%*c\n %s%s",T,E,r(85),11,r(70),r(84),11,r(71),r(83),11,r(72),F,B);}

```

Try it online!

# Answer
> 1 votes
# PHP, ~~236~~ ~~229~~ 226 bytes

```
<?=($a=ord(file_get_contents('php://stdin'))-65)?preg_replace_callback('~\w~',function($m)use($a){return chr((ord($m[0])-65+$a)%26+65);},'   XYZABC
 VW      DE
U          F
T          G
S          H
 RQ      JI
   PONMLK'):'';

```

Try it online!

Pre-golf:

```
<?php
$adjust = ord(file_get_contents('php://stdin')) - 65;
echo preg_replace_callback('~\w~', function($match) use ($adjust) {
    $new = ord($match[0]) - 65;
    $new = ($new + $adjust) % 26;
    $new += 65;
    return chr($new);
}, '   XYZABC
 VW      DE
U          F
T          G
S          H
 RQ      JI
   PONMLK');

```

Explanation:

Using `ord` we convert to an integer between 0 and 255. A is 65 and Z is 90.
Using this knowledge, we take the input and reduce it by 65 so we have an adjustment value.
We then iterate over all characters, call `ord` on them, reduce them by 65, increase them by our adjustment value. Using modulo we loop back down to 0 if they exceed 26.
We then increase them by 65 again and convert them back into letters with `chr`.

Sadly php://stdin can only be interogated once, so we need to pass the input into the function in our loop, preventing us from saving bytes on `use($a)` and having to declare a variable outside the function stops us from cleanly using the `<?=` echo method - we have to wrap everything in a giant ternary.

# Answer
> 1 votes
# Javascript (V8), 316 bytes

```
function a(b){n="abcdefghijklmnopqrstuvwxyz".split(b);n=b+n[1]+n[0],console.log(`   ${n[23]+n[24]+n[25]+n[0]+n[1]+n[2]}\n ${n[21]+n[22]}      ${n[3]+n[4]}\n${n[20]}          ${n[5]}\n${n[19]}          ${n[6]}\n${n[18]}          ${n[7]}\n ${n[17]+n[16]}      ${n[9]+n[8]}\n   ${n[15]+n[14]+n[13]+n[12]+n[11]+n[10]}`)}

```

Try it online

First time trying code golf out. Appreciate any tips / feedback.

Original code before minifying:

```
function a(b){
    var c = ("abcdefghijklmnopqrstuvwxyz").split(b);
    c = b+c[1]+c[0]
    console.log(`   ${c[23]+c[24]+c[25]+c[0]+c[1]+c[2]}\n ${c[21]+c[22]}      ${c[3]+c[4]}\n${c[20]}          ${c[5]}\n${c[19]}          ${c[6]}\n${c[18]}          ${c[7]}\n ${c[17]+c[16]}      ${c[9]+c[8]}\n   ${c[15]+c[14]+c[13]+c[12]+c[11]+c[10]}`)
}

```

# Answer
> 0 votes
# Red, 139 bytes

```
func[a][foreach c{   XYZABC
 VW      DE
U          F
T          G
S          H
 RQ      JI
   PONMLK}[if c > sp[c: c + a % 26 + 65]prin c]]

```

Try it online!

A really naive solution.

# Answer
> 0 votes
# Perl 5 `-p`, 110 bytes

```
$b=/A/?Z:chr(-1+ord);$_=eval("'2XYZABC
 VW5DE
U9F
T9G
S9H
 RQ5JI
2PONMLK'=~y/A-Z/$_-ZA-$b/r");s/\d/$".$"x$&/eg

```

Try it online!

# Answer
> 0 votes
# C (gcc), ~~200~~ ~~198~~ 197 bytes

-3 bytes thanks to ceilingcat.

```
x,z;f(c){char*y,t[27],i=0;for(c-=46;i<14;t[13+i++]=(c-i)%26+65)t[i]=(c+i)%26+65;for(i=-4;++i<4;printf("%*.*s%*.*s\n",3273>>x*3&7,x?:1,y,z,x?:1,y+2*!i+z))z="--*%"[x=abs(i)]-34,y=t+x+(x>2)+13*(i>0);}

```

Try it online!

# Answer
> 0 votes
# APL (Dyalog Classic), 50 bytes

```
⎕a@((-⎕a⍳⍞)⌽∪⌊.5+{3 5.5×1-2 1○○⍵÷¯19}¨⍳38)⊢7 12⍴''

```

Try it online!

# Answer
> 0 votes
# PHP, 131 bytes

```
for(;$s='2YZABCD
 WX5EF
V9G
U9H
T9I
 SR5KJ
2QPONML'[$i++];)echo$s<A?$s<'0'?$s:str_pad('',$s+1,' '):chr(65+(ord($s)+ord($argn))%26);

```

Try it online!

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


title: Stack the Christmas Gifts

text:
# Question
Title: Stack the Christmas Gifts
Someone has been hastily stacking the Christmas presents, and it's quite a mess:

```
           ========================
           |                      |
           ========================
     =============
     |           |
     |           |
     |           |
     |           |
     |           |
     |           |
     =============
        =======
        |     |
        |     |
        |     |
        =======
  ===================
  |                 |
  |                 |
  |                 |
  ===================
=================
|               |
|               |
|               |
|               |
=================
   =======
   |     |
   |     |
   =======

```

Like, seriously, how does that top present even balance. It's probably a hammer. To prevent this tower of presents from crumbling, you're to reorder the presents so they stack nicely:

```
        =======
        |     |
        |     |
        =======
        =======
        |     |
        |     |
        |     |
        =======
     =============
     |           |
     |           |
     |           |
     |           |
     |           |
     |           |
     =============
   =================
   |               |
   |               |
   |               |
   |               |
   =================
  ===================
  |                 |
  |                 |
  |                 |
  ===================
========================
|                      |
========================

```

## The Rules

* Each present consists of a top and bottom of `=` characters, and one or more middle rows, consisting of two `|` separated by spaces. The width of the present is the same in all its rows.
* There are no empty lines.
* Consecutive presents will overlap in at least one column.
* Presents are to be stacked in order of decreasing width. In the event of a tie, the taller present should go below the flatter present.
* Presents should be centred on the present beneath. If the present cannot be placed exactly in the centre (because the difference in widths is odd), you may choose either position that is half a character off the centre.
* You may or may not assume that the input has a single trailing newline, but please state your assumption.
* Your solution does not have to work for an empty input, but must be able to handle a single present.
* You may write a program or function, which takes input via STDIN or function argument and returns the result or prints it to STDOUT.
* This is code golf, so the shortest answer (in bytes) wins.

# Answer
# CJam, ~~81~~ 70 bytes

```
'"qN/{__Sm0=#>}%N*"=
="/"=\"\"="*'"++~]$_W='=/,f{1$'=/,m4/\N/\f{S*\N}}

```

So we have to stack the Christmas presents? This code does it like an actual person would do*.

**First**, we stack all the presents against a wall to easily move them up and down using this code:

```
'"qN/{__Sm0=#>}%N*

```

**then**, we identify each present as a separate item using this code:

```
"=
="/"=\"\"="*'"++~]

```

**then**, we sort the presents based on their heights and widths using this code:

```
$

```

*Till now*, all the gifts have been stacked against a wall in order to have perfect alignment with each other. But as this is Christmas, we want to place the gifts aligned centered like a Christmas tree! This code does that:

```
_W=Af{1$Am4/\N/\f{S*\N}}

```

Here is a step by step output of the code for example in the question:

```
"Step 1 - Stack the presents against a wall";
========================
|                      |
========================
=============
|           |
|           |
|           |
|           |
|           |
|           |
=============
=======
|     |
|     |
|     |
=======
===================
|                 |
|                 |
|                 |
===================
=================
|               |
|               |
|               |
|               |
=================
=======
|     |
|     |
=======

"Step 2 - Identify the presents as a collection of presents";
["========================
|                      |
========================" "=============
|           |
|           |
|           |
|           |
|           |
|           |
=============" "=======
|     |
|     |
|     |
=======" "===================
|                 |
|                 |
|                 |
===================" "=================
|               |
|               |
|               |
|               |
=================" "=======
|     |
|     |
======="]

"Step 3 - Sort on height & width, with presents stacked against a wall to help sort them";
=======
|     |
|     |
=======
=======
|     |
|     |
|     |
=======
=============
|           |
|           |
|           |
|           |
|           |
|           |
=============
=================
|               |
|               |
|               |
|               |
=================
===================
|                 |
|                 |
|                 |
===================
========================
|                      |
========================

"Final step - stack them like a Christmas Tree";
        =======
        |     |
        |     |
        =======
        =======
        |     |
        |     |
        |     |
        =======
     =============
     |           |
     |           |
     |           |
     |           |
     |           |
     |           |
     =============
   =================
   |               |
   |               |
   |               |
   |               |
   =================
  ===================
  |                 |
  |                 |
  |                 |
  ===================
========================
|                      |
========================

```

Try it online here

* Might differ from person to person though :P
> 15 votes

# Answer
# Japt, 18 bytes

```
mx óÈíY b'=²Ãn c û

```

Try it online!

I use a sufficiently different strategy from the other Japt answer that I thought it was worth its own answer. Takes input and output as an array of lines

Explanation:

```
mx                    #Trim leading whitespace from each line
   ó        Ã         #Split the array between lines where:
    ÈíY               # The lines interleaved (e.g. "abc","def" => "adbecf")
        b'=²          # starts with "=="
             n        #Default sorting for "array of arrays of strings"
               c      #Flatten to a single array of lines
                 û    #Pad each line so they are centered

```

I don't know precisely why "default sort" works like that, but I've tested that the taller box of the two with the same width is on the bottom regardless of which comes first in the input.
> 3 votes

# Answer
# Ruby, 164

Neat challenge! Couldn't get it down much further.

```
f=->x{y=x.scan(/\s+=+[\s|]+\s+=+/).sort_by{|p|-p.count(?|)}.sort_by{|p|p.count ?=}
y.map{|p|p.gsub(/^\s+/,'').each_line{|l|puts l.strip.center(y[-1].count(?=)/2)}}}

```

### Explanation

The input `String` is chopped up into an `Array` where each present is an element. Then the array is sorted by the number of pipe characters and sorted *again* by the number of equal signs.

It then removes all leading whitespace and prints each line individually, centered by the width of the largest present.

It behaves the same with or without a trailing newline on the input.

### Readable version

```
f = lambda do |x|
  y = x.scan(/\s+=+[\s|]+\s+=+/)
       .sort_by { |p| -p.count("|") }
       .sort_by { |p|  p.count("=") }

  y.map do |p|
    p.gsub(/^\s+/,'').each_line do |l|
      puts l.strip.center(y.last.count("=") / 2 )
    end
  end
end

```
> 2 votes

# Answer
# 05AB1E, ~~23~~ 20 bytes

```
|ðδÛ»…=
=…=0=:0¡{».c

```

-3 bytes thanks to *@ErikTheOutgolfer*.

Try it online.

**Explanation:**

```
|         # Take the input split by newlines
 ðδÛ      # Remove leading spaces from each line
    »     # And join everything back together again with a newline delimiter
…=
=         # Push string "=\n="
 …=0=     # Push string "=0="
     :    # Replace all "=\n=" with "=0="
0¡        # Now split on "0"
          # (We now have our list of presents without any leading spaces)
  {       # Sort this list (with default string-wise sorting)
   »      # Join the list of presents by newlines
    .c    # Left-focused centralize the string (and output implicitly)

```

**Notes:**

* Odd-width presents are left-focused centralized. This can be changed to right-focused by changing the trailing lowercase `c` to an uppercase `C`.
* The leading `|` can be dropped if we are allowed to take the input as a list of string-lines.
* Assumes the input contains no trailing spaces for any of the presents (similar as the input in the challenge description); trailing newlines are fine, since the `|` removes those anyway.
> 1 votes

# Answer
# Attache, 91 bytes

```
Join&lf@{Center&#(_@-1@0)@>_}@{SortBy[&{#_'#__},Strip@>Lines=>Split[_,/"(?<==)\\s+(?==)"]]}

```

Try it online!

## Ungolfed

```
?? returns [length of first entry, number of entries]
revDim := &{#_'#__}

?? regex
SPLIT_ON_BARRIERS := /"(?<==)\\s+(?==)"

splitPresents[str] := (
    chopped .= Split[str, SPLIT_ON_BARRIERS];;
    normalized .= Strip @> Lines => chopped
)

orderPresents[presents] :=
    SortBy[revDim, presents]

fixPresents[ordered] := (
    ?? number of columns of bottom-most present
    pad_size .= Size[Last[ordered][0]];;
    ?? center each line of each present
    Center&pad_size @> _
)

joinNewlines := Join&lf

stackPresents := joinNewlines@fixPresents@orderPresents@splitPresents

```
> 1 votes

# Answer
# Japt, ~~23~~ ~~20~~ 19 bytes

Similar approach to Kevin's solution. First byte can be removed if we can take input as an array of lines.

```
·mx ·r¥¬·È·Ãq, n ·û

```

Try it

```
·mx ·r¥¬·È·Ãq, n ·û     :Implicit input of string
·                       :Split on newlines
 m                      :Map
  x                     :  Trim
    ·                   :Join with newlines
     r                  :Global replace
      ¥                 :  Shortcut for the == operator. Passing an operator as the first argument of a method in Japt implicitly converts it to a string
       ¬                :  Split
        ·               :  Join with newlines, giving the string "=\n=" to be replaced
         È              :  Pass each match through a function
          ·             :    Split on newlines. As we're working within a string, the resulting array gets cast to a string (i.e., "=\n=" -> ["=","="] -> "=,="
           Ã            :End replace
            q,          :Split on ","
               n        :Sort
                 ·      :Join with newlines
                  û     :Centre pad each line with spaces to the length of the longest

```
> 0 votes

# Answer
# Python 2, ~~221~~ 196 bytes

```
s,a,b,i=[c.strip()for c in input().split("\n")]+["="],[],[],0
exec"a+=[s[i].center(max(map(len,s)))]\nif s[i][0]==s[i+1][0]=='=':b+=[a];a=[]\ni+=1;"*(len(s)-1)
for c in sorted(b):print"\n".join(c)

```

Try it online!

Expects a quoted string without trailing newlines as input.

Not great, but it's the best I can do.
> 0 votes

# Answer
# Perl 5 `-n0`, 123 bytes

```
sub k{pop=~y/=//}say s+^\s*+$"x((k($p[-1])- k$_)/4)+rmge for@p=sort{k($a)- k$b||$a=~y/|//-$b=~y/|//}/\s*(=+[|
]+\s*\=+)/gs

```

Try it online!
> 0 votes

# Answer
> **Javascript** ~~279 bytes~~ 275 bytes

I am something of a novice to code-golf, and not anything like an expert in javascript but the challenge is interesting and fun. I would like to see what tricks a real expert in js would use.

**Assumptions**

* Input and output are arrays of strings
* No blank lines anywhere
* Height of a box is \<= 99 lines (does this disqualify me)?
* Input and output variables are predefined, output being initially an empty array

**Code**

Input is in `g[]`. Output in `m[]`.

```
a=[];s='';b=0;c=0;o=[];g.forEach((t,x)=>{t=t.trim(),c=Math.max(c,t.length);o.push(t);if(s==''){s=t;b=x}else{if(t==s){a.push({"K":s.length*100+x-b,"O":o});s='';o=[]}}});a.sort((p,q)=>{return p.K-q.K});a.forEach((t)=>{t.O.forEach((q)=>{m.push(" ".repeat((c-q.length)/2)+q)})});

```

The code works by

1. building an array of objects, each object representing one box, with two members: K, a sort key being the (width x 100 + height) and O, an array of the (trimmed) strings making up the box. While building the array the code remembers the width of the widest box.
2. The array of box objects is sorted into order by the key K. Where boxes have the same width the key ensures they are sorted by height.
3. After sorting the boxes, the strings for each box are pushed into the output array with leading spaces added, which position the box centrally over the widest one.

Try it online!
> 0 votes

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


title: Concatenate the Cats

text:
# Question
Title: Concatenate the Cats
There is a sentence with many cats:

```
there is a cat house where many cats live. in the cat house, there is a cat called alice and a cat called bob. in this house where all cats live, a cat can be concatenated into a string of cats. The cat called alice likes to purr and the cat called bob likes to drink milk.

```

# The Task

Concatenate (`_`) all pairs of neighbouring words in the sentence and place each in between the any such pair if that pair occurs more than once in the sentence. Note that overlapping counts, so `blah blah` occurs twice in `blah blah blah`.

For example, if `the cat` occurs more then once, add the concatenated words in between them like this: `the the_cat cat`

# Example Output

```
there there_is is is_a a a_cat cat cat_house house where many cats live. in the the_cat cat cat_house house,
there there_is is is_a a a_cat cat cat_called called called_alice alice and a a_cat cat cat_called called called_bob bob.
the the_cat cat cat_called called called_alice alice likes likes_to to purr and the the_cat cat cat_called called called_bob bob likes likes_to to drink milk.

```

Some more examples:

```
milk milk milk       milk milk_milk milk milk_milk milk
a bun and a bunny    a bun and a bunny
milk milk milk.      milk milk milk.
bun bun bun bun.     bun bun_bun bun bun_bun bun bun.

```

# Notes

* All `utf-8` characters are allowed. Meaning that punctuations are part of the input.
* Punctuation becomes part of the word (e.g., with `in the house, is a cat` the word `house,` includes the comma)

# Answer
> 3 votes
# Python 2, ~~99~~ ~~107~~ ~~103~~ 102 bytes

```
def f(s):S=s.split();T=zip(S,S[1:]+[s]);return' '.join(x+(' '+x+'_'+y)*(T.count((x,y))>1)for x,y in T)

```

Try it online!

Fixed the `milk milk milk` style edge cases.

# Answer
> 3 votes
# Jelly,  ~~23 22 21~~  18 bytes

```
Ḳµżj”_$ƝḢKċ@Ị¥?€`K

```

A full program which prints the output.

**Try it online!** Or see a test-suite.

### How?

```
Ḳµżj”_$ƝḢKċ@Ị¥?€`K - Main Link: list of characters T
Ḳ                  - split (T) at spaces (call this W)
 µ                 - start a new monadic chain (i.e. f(W))
       Ɲ           - for neighbouring pairs:
      $            -   last two links as a monad:
   j               -     join with...
    ”_             -     ...underscore character
  ż                - zip (with W) (making pairs of ["left", "left_right"]
                   -               plus a trailing ["rightmost"])
                `  - use this as both left and right arguments of:
               €   -   for each:
              ?    -     if...
             ¥     -     ...condition: last two links as a dyad:
           @       -       with swapped arguments:
          ċ        -         count occurrences of right in left
            Ị      -       is insignificant? (abs(x) <= 1)
        Ḣ          -     ...then: head (   ["left", "left_right"] -> "left"
                   -                    or ["rightmost"] -> "rightmost")
         K         -     ...else: join with space (["same", "same_same"] -> "same same_same")
                 K - join with space characters
                   - implicit print

```

# Answer
> 2 votes
# Zsh, 103 bytes

```
t=($=1)
for b a (${${t:1}:^t})s+=(${a}_$b)
for w ($s)((++i,${#s:#$w}-$#s+1))||s[i]=
echo ${t:^s} $t[-1]

```

Try it online!

The key constructs used here are:

* `${=1}`: splits the first parameter into words (because there are no other flags, the {braces} are optional)
* `${a:^b}`: substitutes array `$a` zipped with array `$b`
* `${a:#b}`: substitutes array `$a` with all instances of `b` removed.
* `${# }`: the length of the contained expansion.
* `echo`: `<<<` leaves extra spaces

If the input is already split into words, 99 bytes.

# Answer
> 2 votes
# Jelly, ~~32~~ 27 bytes

```
;⁶Ḳṡ2W€jj”_W$Ɗ€ĠL’$ƇẎƊ¦Ṗ€ẎK

```

Try it online!

Shorter and more correct! Thanks to @JonathanAllan for highlighting an issue with "milk milk milk"!

A monadic link that takes a Jelly string as its argument and returns a processed Jelly string.

## Explanation

```
;⁶                          | Append a space
  Ḳ                         | Split at spaces
   ṡ2                       | Sliced of length 2
                     Ɗ¦     | At the indices indicated by the following:
               Ġ            | - Group indices of equal values
                   Ƈ        | - Keep only those where the following is non-zero:
                L           |   - Length
                 ’          |   - Decrease by 1
                    Ẏ       | - Tighten (join outermost lists together)
             Ɗ€             | Do the following as a monad:
     W€                     | - Wrap each word in a list
       j    $               | - Join with the following:
        j”_                 |   - The two words joined with "_"
           W                |   - Wrapped in a list
                       Ṗ€   | Remove last member of each list
                         Ẏ  | Tighten (join outermost lists)
                          K | Join with spaces

```

# Answer
> 1 votes
# JavaScript (ES6), 94 bytes

```
s=>s.split` `.map((w,i,a)=>a.some((W,j)=>j!=i&W==w&a[j+1]==(p=a[i+1]))?w+` ${w}_`+p:w).join` `

```

Try it online!

# Answer
> 1 votes
# , 69 bytes

```
;:inv@(a:-.~],@,.a:,~(2(,'_'&,)&.>/\])#&.>~1<1#.[:=/~2<\])' '<;._1@,]

```

Try it online!

# , 56 bytes (but breaks on commas)

```
(a:-.~],@,.a:,~(2(,'_'&,)&.>/\])#&.>~1<1#.[:=/~2<\])&.;:

```

Try it online!

## explanation for both

A bit verbose but the underlying idea is nice, so I'll explain that with pictures:

Let's start with this input:

```
low in xx xx low in bun bun bun bun.

```

First we turn it into words:

```
┌───┬──┬──┬──┬───┬──┬───┬───┬───┬────┐
│low│in│xx│xx│low│in│bun│bun│bun│bun.│
└───┴──┴──┴──┴───┴──┴───┴───┴───┴────┘

```

And then create the underscore concatenation of *every* pair, plus a blank item at the end:

```
┌──────┬─────┬─────┬──────┬──────┬──────┬───────┬───────┬────────┬┐
│low_in│in_xx│xx_xx│xx_low│low_in│in_bun│bun_bun│bun_bun│bun_bun.││
└──────┴─────┴─────┴──────┴──────┴──────┴───────┴───────┴────────┴┘

```

Let's zip these together and see where we're at:

```
┌────┬────────┐
│low │low_in  │
├────┼────────┤
│in  │in_xx   │
├────┼────────┤
│xx  │xx_xx   │
├────┼────────┤
│xx  │xx_low  │
├────┼────────┤
│low │low_in  │
├────┼────────┤
│in  │in_bun  │
├────┼────────┤
│bun │bun_bun │
├────┼────────┤
│bun │bun_bun │
├────┼────────┤
│bun │bun_bun.│
├────┼────────┤
│bun.│        │
└────┴────────┘

```

We notice that if we could keep just the items we want in the right column, we could flatten the whole thing, unbox, and we'd be done.

So we want a filter for the right column. Let's start by treating the consecutive pairs of input words as single units (again, with a blank at the end):

```
┌────────┬───────┬───────┬────────┬────────┬────────┬─────────┬─────────┬──────────┬┐
│┌───┬──┐│┌──┬──┐│┌──┬──┐│┌──┬───┐│┌───┬──┐│┌──┬───┐│┌───┬───┐│┌───┬───┐│┌───┬────┐││
││low│in│││in│xx│││xx│xx│││xx│low│││low│in│││in│bun│││bun│bun│││bun│bun│││bun│bun.│││
│└───┴──┘│└──┴──┘│└──┴──┘│└──┴───┘│└───┴──┘│└──┴───┘│└───┴───┘│└───┴───┘│└───┴────┘││
└────────┴───────┴───────┴────────┴────────┴────────┴─────────┴─────────┴──────────┴┘

```

The filter we seek is simply any element that occurs more than once. To find this we'll create a function table of equality:

```
1 0 0 0 1 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
1 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1

```

And sum it rowise or colwise (the direction doesn't matter, since it's symmetric):

```
2 1 1 1 2 1 2 2 1 1

```

And find all entries greater than 1:

```
1 0 0 0 1 0 1 1 0 0

```

This filter is all we need to carry out our plan from above and arrive at the answer.

---
Tags: code-golf, word-puzzle
---


title: Transposed, primes, oh my!

text:
# Question
Title: Transposed, primes, oh my!
The task is simple: your program reads an integer as an input, and prints whether it is a prime or not. You can print "yes/no", "true/false" or anything what unambiguously identifies the result.

The challenge is, the code has to work with its rows and columns transposed.

To exclude the obvious solution (shortest "simple" solution repeated vertically char-by-char with the use of comments), the metric is a little bit different from the usual code-golf:

**Because formatting is very important in this challenge**, the code size is measured in the area of the smallest rectangle the code fits in. In other words, whitespace does count, and the lines should be filled to be of equal length (you don't have to actually do it when you post the solution, for simplicity's sake). For example

```
int main()
{
    return 0;
}

```

would have a size of 4\*13 = 52, <sub>(and obviously it does not fit either of the two criteria: prime detection and transposable.)</sub>

Smallest size wins.

You can use any language, and any library function except if the sole purpose of that function is to find, generate, or detect primes.

# Edit:

While the winner would probably be the Golfscript solution, I'll award a 50 point bounty for the best C or C++ solution!

# Answer
## GolfScript, 13 × 1

```
~.,2>{1$\%!}?

```

GolfScript strikes again!

Repeats the input if it is prime, otherwise prints the input concatenated with its smallest proper divisor. Yes, I know that's stretching the definition of "anything what unambiguously identifies the result", but doing anything fancier would cost a few extra characters. If you want nicer output, appending the three characters `;]!` to the code yields `1` for primes and `0` for composite numbers.

The algorithm is really inefficient, just brute force trial division from 2 to *n*−1. Most GolfScript operators are only single characters, so this code works just as well transposed. Annoyingly, though, the assignment operator `:` doesn't allow whitespace between itself and its target, so I had to do this entirely without variables.
> 7 votes

# Answer
## C, 2\*70 2\*60

Prints `y` for primes, nothing otherwise.
**EDIT**: Changed code to save 10 chars. Must be run without paramters (so `m=1`).

```
main(m,n){for(scanf("%d",&n);n%++m&&n>1;);n-m||puts("y");}/*
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/

```

The method for handling the transposition is quite generic, and can be applied to any program.
It's based on converting this:

```
abcd/*
\\\\*/

```

To this:

```
a\
b\
c\
d\
/*
*/

```

And both mean simply `abcd`.
> 21 votes

# Answer
# C - 13x13

Reads the input from stdin and prints a `1` for prime and a `0` for not prime.

```
////m(i;(a=)<
////aans")a;2
//:Di)tc%;;p)
//O n{ adfau+
main//bn"o%t4
(a){///f,r-c8
int b///&(-h)
;scanf///bba;
("%d",&///;r}
a);for(b///(
=a;a%--b;//(
);putchar((b
<2)+48);}

```

edit: compiles with gcc and clang now, other compilers weren't tested
> 15 votes

# Answer
## C, 12x12 chars

A two-dimensional solution, unlike my other answer, based on the same code (and like it, prints `y` for prime, nothing for composite).
The structure is similar to Quasimodo's answer, but my code is shorter, and I think my usage of comemnts is a bit more efficient, so I can fit 12x12.

```
////m()s";np
////am{c%n>u
////i,fad%1t
////nnon"+;s
main//rf,+)(
(m,n//((&m;"
){for(//n&ny
scanf(//)&-"
"%d",&n)//m)
;n%++m&&//|;
n>1;);n-m||
puts("y"); }

```
> 12 votes

# Answer
## Perl, 14 x 14

I think I'm getting the hang of this. Specify the number as a command line argument, outputs `0` or `1`. Probably more room for improvement.

```
$   n=pop;$p|=
 !  ($n%$_)for
  2 ..$n/2;
   print!$p+m~
n(.r
=$.i
pn$n
o%nt
p$/!
;_2$
$);p
pf +
|o m
=r ~

```
> 7 votes

# Answer
# Q

Abused comments for a symmetric, character inefficient solution.

```
/{/////////////////////////////////
{(~)any 0=mod[x;2+(!)x-2]}"I"$(0:)0
/~
/)
/a
/n
/y
/
/0
/=
/m
/o
/d
/[
/x
/;
/2
/+
/(
/!
/)
/x
/-
/2
/]
/}
/"
/I
/"
/$
/(
/0
/:
/)
/0

```

Takes input from STDIN, returns a boolean.
> 3 votes

# Answer
# 05AB1E, ~~1x5~~ 1x3 (~~5~~ 3 bytes)

This isn't one big program; each line is a separated alternative program to tackle the prime check (without using the prime builtin).

```
ÑPQ
ÒgΘ
ÒQP
ÕαΘ
fQO
fs¢
f`Q

```

-2 bytes thanks to *Grimy*.

Whitespaces in between lines are no-ops in 05AB1E, and since I only use 1-byte commands, this works fine after transposing.

Outputs `1`/`0` for truthy/falsey respectively.

Try the first one online or verify some more test cases for all of them (with eval builtin `.V`).
Transposed: Try the first one online.

**Explanation:**

```
Ñ    # Get a list of all divisors of the (implicit) input-integer
     # (which would be only 1 and the integer itself for primes)
 P   # Take the product of that list
  Q  # And check if it's equal to the (implicit) input-integer

Ò    # Get a list of all prime factors of the (implicit) input-integer
 g   # Get the amount of those prime factors by taking the length of the list
  Θ  # Check if that's equal to 1 (so only itself is a prime factor)

Ò    # Get a list of all prime factors of the (implicit) input-integer including duplicates
 Q   # Check for each if it's equal to the (implicit) input-integer
     # (1 if truthy; 0 if falsey)
  P  # Take the product of those checks (resulting in either 1 or 0 as well)

Õ    # Get the Euler totient of the (implicit) input-integer
 α   # Take the absolute difference with the (implicit) input-integer
  Θ  # Check if that's equal to 1

f    # Get a list of all prime factors of the (implicit) input-integer without duplicates
 Q   # Check for each if it's equal to the (implicit) input-integer
  O  # And take the sum of that (resulting in either 1 or 0)

f    # Get a list of all prime factors of the (implicit) input-integer without duplicates
 s   # Swap to get the (implicit) input-integer
  ¢  # And count how many time it occurs in the list

f    # Get a list of all prime factors of the (implicit) input-integer without duplicates
 `   # Dump all the content of this list onto the stack
  Q  # Check if the top two values are equal, or if only a single value is present, it will
     # use the (implicit) input-integer as second value

     # For all these program the same applies at the end:
     # (implicitly output the result with trailing newline)

```

NOTE: If only a truthy/falsey value is valid, and it doesn't necessary has to be distinct, either `Òg` or `Õα` could be used as valid 2-byters, since only `1` is truthy in 05AB1E, and everything else is falsey: Try both of them for some test cases.

If builtins were allowed, a single `p` would have sufficed: Try it online or verify some more test cases.
> 1 votes

# Answer
# APL (Dyalog Unicode), 10x11

```
{⍵∊∘.×⍨1↓⍳⍵
 ∊
 ∘
 .
 ×
 ⍨
 1
 ↓
 ⍳
 ⍵         }

```

Try it online!

Corrected the function to comply with the specifications. Thanks @Adám for the heads-up.

Returns **0 for truthy, 1 for falsy**.

### How

```
{⍵∊∘.×⍨1↓⍳⍵ ⍝ Dfn. everything below this is a noop up until closing the brace
         ⍳⍵ ⍝ Range [1..arg]
       1↓   ⍝ Dropping the first element (yields [2..arg])
   ∘.×⍨     ⍝ Multiplication table for each element in the vector
 ⍵∊         ⍝ Check if the argument is in the table.

```

The transposed version is the exact same.
> 0 votes

# Answer
# Runic Enchantments, 7×1

```
v̀i'PA@

```

Try it online!

Runic cares not for your feeble attempts at source rearrangement! Conforming to the requirement of still functioning after having the source transposed cost +3 bytes (+2 rectangle width) for the reflection modifier and entry point.

Transposed or transposed, but leaving the combining character attached to its parent.
> 0 votes

# Answer
# dzaima/APL, 8×9 = 72

```
{t←0,1↓⍳⍵
 ←⍵∊∘.×⍨t
 0∊
 ,∘
 1.
 ↓×
 ⍳⍨
 ⍵t     }

```

Try the original or transposed!
> 0 votes

# Answer
# Python 3, 28 x 28 size

```
lambda i:i>1 and           \
all(i%j for j in range(2,i))
ml="""                     "
b("                        "
di"                        "
a%"
 j
i
:f
io
>r
1
 j
a
ni
dn

 r
 a
 n
 g
 e
 (
 2
 ,
 i
 )
\)"""

```

Try it online!
> 0 votes

# Answer
# JavaScript (Node.js), ~~26~~ 25x5

```
n=>!( P/**//*-
= * P =* /** -         r
>**/= r=>n%--r?P(r):~-r)(
/*////=  %  *        /*/n
*1 )//>*/   /        *//)

```

Try it online!

Transposed:

```
n=>/*
= **1
>**/
! //)
(P=//
   //
P=r=>
/*= *
* > /
*/n%
/*%
/*-
* -*/
--r
  ?
  P
  (
  r
  )
  :
  ~
  -/*
  r*/
 r)//
  (n)

```

Try it online!
> 0 votes

---
Tags: code-challenge, decision-problem, primes, radiation-hardening
---


# Question
Title: triplegolf - not only the source code length counts!
The goal of this challenge is to write a program where the length of the following three are exactly the same:

* the length of the source code
* the length of the output it prints to the standard output
* the length of the compiler warnings it generates with the (unmodded) compiler of your choice

**The winner is the shortest code to fulfill all three criteria, and has to be at least 1 character long.**

To spice things up, if the output has less than three different characters, it gets a **5 point penalty** added to the length for each one (so +10 if only a single type, +5 for two).

(Newlines count either as 1 or 2 characters, your choice, but it has to be consistent through all three criteria. Leading and trailing white-spaces are ignored in all lines in all three criteria)

In case of equal score, the one printing the most interesting result (instead of garbage) is the winner.

# Answer
## Bash, 23 characters

Error:

```
bash: /: Is a directory

```

Source:

```
echo       $0-$01234;/;

```

Output:

```
/bin/bash-/bin/bash1234

```

## Brainf\*ck, 32 characters

This code executes for about 3 seconds and stops and displays the following error and output.

Error:

```
bff: out of memory (-2058691272)

```

Source:

```
+++++[......-]..+[>>>>>>>>>>>>-]

```

Output: (Hexdump)

```
0505 0505 0505 0404 0404 0404 0303 0303
0303 0202 0202 0202 0101 0101 0101 0000

```

## C, 35 characters

Warning:

```
b.c:1:30: warning: division by zero

```

Source and Output:

```
main(){system("cat "__FILE__)/0;;;}

```

## PHP, 50 characters

Warning:

```
PHP Warning:  Division by zero in /tmp/3 on line 1

```

Source and Output:

```
<?php echo (0/0).''.file_get_contents(__FILE__);?>

```
> 14 votes

# Answer
## C - 48 chars

```
main(i){while(++i<49)putchar(i);putchar('\z');}

```

Note: includes a final (Unix-style) newline.

Output from `gcc a.c` reads:

```
a.c:1:41: warning: unknown escape sequence '\z'

```

The output from `a.out` is mostly non-printing chars, so here's what it looks like after piping through hexdump:

```
00000000: 0203 0405 0607 0809 0A0B 0C0D 0E0F 1011  ................
00000010: 1213 1415 1617 1819 1A1B 1C1D 1E1F 2021  .............. !
00000020: 2223 2425 2627 2829 2A2B 2C2D 2E2F 307A  "#$%&'()*+,-./0z

```
> 8 votes

# Answer
# JavaScript, 63 ~~66~~

```
!function x(){console.log(x+'...');eval(Array(33).join('$'))}()

```

The output is:

```
function x(){console.log(x+'...');eval(Array(33).join('$'))}...

```

In Chrome, the error is:

```
ReferenceError: $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ is not defined

```
> 4 votes

# Answer
# Visual Basic .NET, 185

Gee, `vbc` is pretty verbose with its compilation warnings. Anyway, the code is this:

```
Public Module Main
    Public Sub Main()
        Console.WriteLine(New String("a"c,185))
    End Sub

    Public Function A()
        'This is actually just padding.
        'Hi
    End Function
End Module

```

(Note that they're supposed to be tabs, not spaces.)

The output is this:

```
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

```

And the compiler warning is this:

```
warning BC42105: Function 'A' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.

    End Function
    ~~~~~~~~~~~~

```

(This time, it's actually four spaces, not tabs.)
> 3 votes

# Answer
# Zsh, 20 bytes

```
<<<   $-$_$_$_$_$_
[

```

The problem we face here is alluded to in a comment above: Zsh prints the **program name** in addition to the line number before every error. The solution here uses a one-character filename to abuse this. I've wrapped it up in a helper script to show exactly what it prints, and used `wc -c` on stderr, stdout, and the source file.

Output: `569Xcatcatcatcatcat` followed by a newline
Errors: `s:[:2: ']' expected` followed by a newline

---

EDIT: Alternate 20 byte solution with no file restriction:

```
<<<$-$-$-$-$_>&1 >&2

```

Try it online!

# Zsh, `zsh -x`, 10 bytes

```
<<<$_$_$_

```

`-x` flag enables xtrace. This again requires a single-character filename. Try it online!

# Zsh `zsh -JNTwEDY`, 12 bytes

```
<<<$->&1 >&2

```

Shortest `-flag` answer with no filename requirement. Sets more flags, and `$-` prints them all. Try it online!
> 3 votes

# Answer
# JavaScript (Firefox 54), 34 bytes

```
alert((f=function(x)1234)(56)+f+f)

```

Outputs:

```
1234function(x)1234function(x)1234

```

And it sends this warning to the browser console:

```
expression closures are deprecated

```

It looks like this in my copy of Firefox Developer Edition (54.0a2). It may work in other versions of Firefox as well.
> 2 votes

# Answer
## Ruby, 48 characters

```
IO=1;puts ?a*48;# let's make it 48 bytes long :)

```

Outputs

```
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

```

Warns

```
r.rb:1: warning: already initialized constant IO

```

(the file is r.rb, I removed the path, if you run it from irb, you'll get (irb):1: warning...)

There is the warn method in Ruby, but it just outputs its arguments to $stderr, making it look less like a warning.
> 2 votes

# Answer
# Python, 57 bytes

Other interpreters may display the warning differently. This was only tested to work on TIO.

```
from warnings import*
print("prt"*19)
warn("Warning...!")

```

**Try it online**

**Output**

```
prtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprt

```

**Warning**

```
.code.tio:3: UserWarning: Warning...!
  warn("Warning...!")

```

Note that the leading spaces are not counted toward the byte count. If the leading spaces were not ignored, this could be done in 51 bytes.
> 1 votes

# Answer
# Javascript (ES6), ~~32~~ 30 bytes

```
Screen(console.log(Function));

```

prints

```
ƒ Function() { [native code] }

```

in Chrome, and then throws

```
TypeError: Illegal constructor

```

## My original 32 byte solution:

```
(x=y=>console.log(x+!0+10)||z)()

```

first, prints

```
y=>console.log(x+!0+10)||ztrue10

```

And throws the error

```
ReferenceError: z is not defined

```
> 1 votes

# Answer
## VBA, 39 Bytes

Not sure if this qualifies, given the compiler constraint, but:

**Input:** (in the immediate window)

```
For i=1 To 39:a=a & Chr(i):Next:Print a

```

*The output includes non-printing characters that don't play well in this window.
> 0 votes

# Answer
# Perl 6, 10 bytes

```
dd say 1e9

```

Try it online!

Prints `1000000000` to STDOUT, and `Bool::True` to STDERR. Both produce a trailing newline, but trailing whitespace is ignored in this challenge. `dd` is a Rakudo specific debugging function
> 0 votes

---
Tags: code-golf
---


title: Just repeat yourself

text:
# Question
Title: Just repeat yourself
Write a program that outputs

```
Do not repeat yourself!

```

Your program code must respect the following constraints :

* its length must be an even number
* each character that is in position `2n` (where `n` is an integer \> 0) must be equal to the character in position `2n-1`. The second character of the program is equal to the first, the fourth is equal to the third, etc.

Newlines count as characters!

This is code-golf, so the shortest code wins!

## Examples

`HHeellllooWWoorrlldd` is a valid program

`123` or `AAABBB` or `HHeello` are incorrect

## Verification

You can use this CJam script to verify that your source code is valid. Simply paste your code into the "Input" box and run the script.

# Answer
> 52 votes
# Hexagony, ~~166~~ ~~126~~ 124 bytes

```
\\;;;;33rr''22DD..));;;;;;oo;;}}eeoo\\@@nn;;;;ee;;;;aass&&;;uuoo;;;;..\\\\;;ttee..pp;;tt;;;;..rr;;''ll..'';;;;..;;}}ff..}}yy

```

Inserting the implicit no-ops and whitespace, this corresponds to the following source code:

```
       \ \ ; ; ; ; 3
      3 r r ' ' 2 2 D
     D . . ) ) ; ; ; ;
    ; ; o o ; ; } } e e
   o o \ \ @ @ n n ; ; ;
  ; e e ; ; ; ; a a s s &
 & ; ; u u o o ; ; ; ; . .
  \ \ \ \ ; ; t t e e . .
   p p ; ; t t ; ; ; ; .
    . r r ; ; ' ' l l .
     . ' ' ; ; ; ; . .
      ; ; } } f f . .
       } } y y . . .

```

I'm sure it's possible to shorten this even more, and maybe even solve it in side-length 6, but it's getting tricky...

## How it works

Diagram generated with Timwi's Hexagony Colorer.

The code is completely linear. The `\` right at the start redirects the IP into a diagonal, such that we don't need to worry about the doubled characters at all. The coloured paths are executed in the order orange/red, blue/grey, green, purple (when there are two paths of the same colour, the left-hand path is executed first, before wrapping around to the right-hand one).

If we ignore no-ops, mirrors and commands which are overridden by others, the linear code comes down to this:

```
D;o;&32;}n;o;t;';}r;e;p;e;a;t;';}y;o;u;r;s;e;l;f;');@

```

Letters in Hexagony just set the current memory edge's value to the letter's character code. `;` prints the current memory edge as a character. We use `&` to reset the memory edge to `0` and print a space with `32;`. `}` moves to a different edge, so that we can remember the `32` for further spaces. The rest of the code just prints letters on the new edge, and occasionally moves back and forth with `';}` to print a space. At the end we move to the space edge again with `'`, increment the value to 33 with `)` and print the exclamation mark. `@` terminates the program.

# Answer
> 44 votes
# GolfScript, ~~130~~ ~~84~~ 76 bytes

```
22..!!..00)){{DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff}}``%%>><<[[33]]++

```

Try it online in Web GolfScript.

### How it works

The GolfScript interpreter starts by placing an empty string on the stack.

```
22 # Push 22.
.. # Push two copies.
!! # Negate the last copy twice. Pushes 1.
.. # Push two copies.
00 # Push 0.
)) # Increment twice. Pushes 2.

   # STACK: "" 22 22 1 1 1 2

{{DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff}}

`` # Push a string representation of the string representation of the block.

   # This pushes "{{DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff}}" (with quotes).

%% # Take every second element of that string, then every element of the result.
>> # Discard the first element of the result. Repeat.
<< # Truncate the result to length 22. Repeat.
[[ # Begin a two-dimensional array.
33 # Push 33, the character code of '!'.
]] # End the two-dimensional array.
++ # Concatenate the empty string, the 22-character string and the array [[33]].

```

Concatenating an array with a string flattens, so the result is the desired output.

# Answer
> 39 votes
# Unary, ~1.86 × 10222

Simple brainfuck -\> unary answer. Very sub-optimal ;).

The program consists of an even number of 0’s; specifically:

> 1859184544332157890058930014286871430407663071311497107104094967305277041316183368068453689248902193437218996388375178680482526116349347828767066983174362041491257725282304432256118059236484741485455046352611468332836658716

of them.

Original brainfuck code:

```
++++[++++>---<]>+.[--->+<]>+++.[--->+<]>-----.+[----->+<]>+.+.+++++.[---->+<]>+++.---[----->++<]>.-------------.+++++++++++.-----------.----.--[--->+<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.---.+.++++[->+++<]>.+++++++.------.[--->+<]>-.

```

# Answer
> 35 votes
# Ruby - 2100 1428 1032 820 670 bytes

This assumes the output can be a return value from a function (it wasn't specified that the output needs to be to STDOUT)

Code:

```
((((((((((((((((((((((((((((((((((((((((((((((""<<66++11**00++11**00))<<99++11++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11))<<99++11++11**00))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11++((11**00<<11**00<<11**00))))<<99++11**00++11**00))<<99++11++11**00++11**00))<<99++11**00++11**00))<<88++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++22))<<99++11++11**00))<<99++((33>>11**00))++11**00++11**00))<<99++11++((11**00<<11**00<<11**00))))<<99++((33>>11**00))))<<99++11**00++11**00))<<99++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++11**00++11**00++11**00))<<33))

```

The trick is to build the string from an empty string `""` using the append operation `<<` and the ASCII codes of the characters.

To get the numbers for the ASCII codes I'm trying to decompose the number into values I can easily generate. For example ASCII `90` is just `88+1+1`, which is:

* `88` is okay on it's own
* `11**00` is `11^0`, which is simply `1`

Fortunately both `++` and `--` would mean `add` in ruby, so I can write `90` as `88++11**00++11**00`

There are some tricks to get to some numbers easier than just adding 1s, here is the code I'm using to generate the above (which includes all mappings I'm using):

```
d = "Do not repeat yourself!"

d.each_char do |c|
  print "(("
end

print '""'

VALUES = [
  [0,'00'],
  [1,'11**00'],
  [4,'((11**00<<11**00<<11**00))'],
  [5,'((11>>11**00))'],
  [11,'11'],
  [16,'((33>>11**00))'],
  [22,'22'],
  [27,'((55>>11**00))'],
  [33,'33'],
  [38,'((77>>11**00))'],
  [44,'44'],
  [49,'((99>>11**00))'],
  [55,'55'],
  [66,'66'],
  [77,'77'],
  [88,'88'],
  [99,'99']
].reverse

d.each_char do |c|
  print "<<"
  num = c.ord
  while num != 0
    convert = VALUES.find{|val|val.first<=num}
    print convert.last
    num -= convert.first
    print "++" unless num == 0
  end
  print "))"
end

```

I'm still thinking about other tricks to decrease the characters required to get to a number.

Note that if you use the `-rpp` flag, and add `pp` to the start of the code like so:

```
pp((((((((((((((((((((((((((((((((((((((((((((((""<<66++11**00++11**00))<<99++11++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11))<<99++11++11**00))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11++((11**00<<11**00<<11**00))))<<99++11**00++11**00))<<99++11++11**00++11**00))<<99++11**00++11**00))<<88++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++22))<<99++11++11**00))<<99++((33>>11**00))++11**00++11**00))<<99++11++((11**00<<11**00<<11**00))))<<99++((33>>11**00))))<<99++11**00++11**00))<<99++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++11**00++11**00++11**00))<<33))

```

then for extra 2+4 bytes this can function as a fully complete program, but it will print an extra `"` before and after the required string:

Example:

```
$ ruby -rpp golf.rb
"Do not repeat yourself!"

```

# Answer
> 23 votes
# \>\<\>, 174 bytes

```
vv

77

99

**

00

77

bb

**

pp

""

!!

ff

ll

ee

ss

rr

uu

oo

yy

tt

aa

ee

pp

ee

rr

tt

oo

nn

oo

DD

""

~~

oo

ll

11

==

;;

00

66

bb

**

..

```

Thankfully, in a sense the restriction doesn't apply vertically. However, the biggest problem is that we need to double every newline.

The code that runs roughly goes like this:

```
v            Redirect instruction pointer to move downwards
79*07b*p     Place a ? on row 77 before the first ;
"..."        Push "Do not repeat yourself!" backwards, riffled between spaces

[main loop]
~o           Pop a space and output a char
l1=?;        If there is only the final space left, halt
06b*.        Jump back to the start of the loop

```

Note that the program has no double spaces — when in string mode, \>\<\> pushes spaces for empty cells. Conversely, however, this means that a solution using `g` (read single cell from source code) would be trickier, since what spaces are in the program become NULs when read.

(Note: This can be 50 bytes shorter if it terminates with an error, but I like it this way.)

# Answer
> 20 votes
# Sclipting, ~~186~~ 146 bytes

> 끄끄닶닶긂긂닦닦닶닶덇덇긂긂댧댧뉖뉖댇댇뉖뉖눖눖덇덇긂긂뎗뎗닶닶덗덗댧댧댷댷뉖뉖닆닆뉦뉦긒긒
>
> 껢껢鎵鎵❶❶合合虛虛替替標標現現併併一一終終

To be clear, there are three lines of code, the middle of which is empty, because the newline needs to be duplicated. The byte count is based on UTF-16 encoding.

# Explanation

The block of Korean characters at the start pushes the string `"DDDof� \"\u0002nf�of�twG \"\u0002rw'efVpw\aefVaf\u0016twG \"\u0002yw�of�uwWrw'sw7efVlf�fff!\"\u0012"`. You will notice that every *third* character is a character we want; the rest is gibberish. Here’s why:

In Sclipting, two Korean characters encode three bytes. Thus, each Korean character effectively encodes 12 bits. To get a string starting with `D`, the first 8 bits have to be `0x44`; the rest don’t matter, but since we have to repeat every character, the 12th to 20th bits are also going to be `0x44`. Thus, we will have a value of the form `0x44n44n` for some *n*, which decomposes into the three bytes `0x44 0xn4 0x4n`.

For the `o`, which is `0x6F`, we get the bytes `0x6F 0xn6 0xFn`.

Since I’m lazy, I started by encoding `"DDDooo nnnooottt (etc.)"` and then replaced every other character with the previous, which is why I get `0x444444` = `"DDD"` for the `D` and `0x6F66F6` = `"of�"` for the `o`. The  is there because `0xF6` by itself is invalid UTF-8 encoding.

Now, back to the program. The rest of the program proceeds as follows:

> 껢껢 — pushes the string `".\"�"`
>
> 鎵鎵 — removes the last character twice, leaving us with `"."`
>
> ❶❶ — two duplicates. Stack now: `[".", ".", "."]`
>
> 合合 — concatenate twice. Stack now: `["..."]`

Now, what I *want* to do next is use `"..."` as a regular expression so that I can match three characters from the original string at a time, using the 替...終 loop construct. However, since every instruction is duplicated, I need to have *two* such regular-expression loops nested inside each other, and if the stack underruns I get a runtime error. Therefore,

> 虛虛 — push the empty string twice

and *then* start the loops. This way, the outer loop iterates only once because it matches the regular expression `""` against the string `""`, which yields a single match. The inner loop runs once for every match of `"..."` against the big string. The body of the loop is:

> 標標 — push two marks onto the stack. Stack now: `[mark mark]`
>
> 現現 — push two copies of the current regex match. Stack now: `[mark mark "DDD" "DDD"]`
>
> 併併 — concatenate up to the first mark. Stack now: `["DDDDDD"]`
>
> 一一 — take first character of that string, and then (redundantly) the first character of that. Stack now has the character we want.

The inner loop ends here, so every match of the regular expression is replaced with the first character of that match. This leaves the desired string on the stack.

Then the outer loop ends, at which point the desired string is taken off the stack and the only match of `""` in the string `""` is replaced with it, leaving the desired string once again on the stack.

# Answer
> 12 votes
# Labyrinth, 528 bytes

```
66))__vv          ..33::00&&__vv          ..44__99||__vv          ..33::00&&__vv            ..99))__vv            ..99))__vv      ..44__88$$__vv          ..22__99++__vv          ..22__99$$__vv            ..22__99))$$__vv      ..33__77$$__vv            ..33__vv

      ..44__99||__^^          ..11__99++__^^          ..44__88$$__^^          ..44((__88$$__^^      ..11))__99++__^^      ..99((__^^          ..33::00&&__^^          ..44__99||__^^          ..44((__88$$__^^            ..99))__^^          ..11__99$$((__^^    ..@@

xx

```

The double newlines hurt, but at least this proves that it's doable!

Each character is printed one-by-one, first by forming the code point then printing a single char. The code points are formed by:

```
D 68  66))
o 111 44__99||
  32  33::00&&
n 110 11__99++
t 116 44__88$$
r 114 44((__88$$
e 101 99))
p 112 11))__99++
a 97  99((
y 121 22__99++
u 117 22__99$$
s 115 22__99))$$
l 108 33__77$$
f 102 11__99$$((
! 33  33

```

where

```
)(        Increment/decrement by 1 respectively
&|$       Bitwise AND/OR/XOR respectively
+         Add
:         Duplicate
_         Push zero
0-9       Pop n and push n*10+<digit>

```

The unusual behaviour of Labyrinth's digits is exploited in `33::00&&`, which is actually

```
[33] -> [33 33] -> [33 33 33] -> [33 33 330] -> [33 33 3300] -> [33 32] -> [32]
     :          :             0              0               &          &

```

Each single char is printed with the mechanism

```
__vv

  ..

xx

```

The `xx` exist only to pad the grid so that it's 5 high. First the `__` push two zeroes, then we hit a grid rotation operator `v`. We pop a zero and rotate:

```
__ v
  v
   .
  .
xx

```

and again:

```
__ v

  v.

xx.

```

We then move rightwards to the `.` on the third row, thus executing the print command only once.

# Answer
> 11 votes
# CJam - 176 136 bytes

```
66))HH77++GG00++BB88++HH77++EE88++GG00++DD88++99))CC88++99))AA77++EE88++GG00++BB99++HH77++KK77++DD88++JJ77++99))AA88++II66++33]]{{cc}}//

```

*Thanks to Sp3000 for dividing my program size by two :-)*

**Explanation**

* The codes `HH77++`, `GG00++`, ... compute the integer ascii code of the characters by adding numbers (for example: \`HH77++' pushes 17, 17 and 77 on the stack, then add these 3 numbers)
* the portion of code at the end `]]{{cc}}//` loops through the ascii codes and convert them to characters.

Try it here

# Answer
> 11 votes
# Self-modifying Brainf\***, 72 bytes

Note that `\x00` represents a literal `NUL` hex byte (empty cell). The source code is placed on the tape, left of the starting cell.

```
!!fflleessrruuooyy  ttaaeeppeerr  ttoonn  ooDD\0\0<<<<<<++[[<<]]<<[[..<<]]

```

### Explanation

```
!!fflleessrruuooyy  ttaaeeppeerr  ttoonn  ooDD  The string on the tape for easy printing
\x00\x00                                        A separator to make printing shorter
<<<<<<++                                        Change first '.' to '0' (comment)
[[<<]]<<                                        Move to separator, then left to string
[[0.<<]]                                        Print string

```

Also, before making this program, I was making one using only BF characters in the source. It's possible! It's also much longer, since for an odd ASCII value, I was going to create double the value, then divide by two. Somewhat shorter would be modifying the entire source to generate odd values to start with.

# Answer
> 8 votes
# Jelly, 66 bytes

```
““DDoo  nn““oott  rreepp““eeaatt  yyoouurrss““eellff!!””ṛṛḷḷWWQQ€€

```

Try it online!

### Factoid

The program still works if you remove every second character.

Try it online!

### How it works

```
““DDoo  nn““oott  rreepp““eeaatt  yyoouurrss““eellff!!”

```

returns an array of string. The literal begins with a , ends with a , and the strings are delimited internally by . The result is

```
["", "DDoo  nn", "", "oott  rreepp", "", "eeaatt  yyoouurrss", "", "eellff!!"]

```

The link's argument and the return value are set to this array of strings, then the remainder of the source code is executed.

```
<literal>”ṛṛḷḷWWQQ€€  Argument/return value: A (string array)

         ”ṛ           Yield the character 'ṛ'.
           ṛ          Select the right argument of 'ṛ' and A: A.
            ḷ         Select the left argument of A and A: A.
              W       Wrap; yield [A].
             ḷ        Select the left argument of A and [A]: A.
               W      Wrap; yield [A].
                Q     Unique; deduplicate [A]. Yields [A].
                 Q€€  Unique each each; for each string s in A, deduplicate s.

```

# Answer
> 5 votes
# MSM, ~~270~~ 160 bytes

```
!!'',,ff'',,ll'',,ee'',,ss'',,rr'',,uu'',,oo'',,yy'',,  '',,tt'',,aa'',,ee'',,pp'',,ee'',,rr'',,  '',,tt'',,oo'',,nn'',,  '',,oo'',,DD'',,......................

```

My first MSM program!

String output in MSM is done by pushing the individual characters onto the stack and joining them into a single string via `.`, e.g.

```
!olleH.....

```

The number of `.` is one less than the number of characters. For `Do not repeat yourself!` we need 22 `.`s. Luckily this is an even number, so we have 11 doubles

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

```

Putting the letters in front of it requires some more effort. The pattern

```
cc'',,

```

does the trick for each character `c`. It evaluates as follows

```
cc'',,            push c (remember: commands are taken from the left and operate on the right)
c'',,c            push c
'',,cc            quote ' and push
,,cc'             pop
,cc               pop
c                 voilà!

```

We need 23 such patterns starting with `!!'',,` and ending with `DD'',,` followed by the 22 join commands `.`.

# Answer
> 5 votes
# Gammaplex, 66 bytes

```
\\

XX""!!fflleessrruuooyy  ttaaeeppeerr  ttoonn  ooDD""XXXXrrRREE

```

Gammaplex is a 2D language that uses the position of the first newline as the line length, and ignore all other newlines.

# Answer
> 5 votes
# Befunge 98, 70 66 bytes

Try it online!

After my invalid answer, here's a better one that actually fits the challenge!

```
2200**xx""!!fflleessrruuooyy  ttaaeeppeerr  ttoonn  ooDD��""kk,,@@

```

(Thanks to Martin Ender for suggesting the use of `��`, character 0x17, instead of `88ff++`)

Explanation:

```
2200          Push 2, 2, 0, and 0 onto the stack
*             Multiply 0 and 0, yielding 0
*             Multiply 2 and 0, yielding 0
              The stack is now [2, 0]
x             Pop a vector off the stack and set the instruction pointer delta to that
              The instruction pointer is now skipping over every other character, since the delta is (2, 0)
"!f ... oD�" Push the string onto the stack, with the number 23 (number of characters in the string) at the top
k,            Pop characters off the stack and print them, 23 times
@             End the program

```

# Answer
> 5 votes
# Backhand, 54 bytes

```
vv""!!fflleessrruuooyy  ttaaeeppeerr  ttoonn  ooDD""HH

```

Try it online!

Since Backhand's pointer already moving at three cells a tick, all we need to do is decrease that to 2 using `v`

# Answer
> 4 votes
# DC, ~~348~~ ~~346~~ ~~342~~ ~~306~~ ~~290~~ 278 bytes

File `dnr6.short.dc` (without trailing newline):

```
AAzz--22222222vvPPAAAAAAAAvvPP88vvFFFFFFFFvv00++AAzz--PP11vvFFFFFFFFvv00++AAAAAAvvPP11vvEEEEEEEEvv00++OOOO//44999999vv++PP77II++OOOO//44999999vv++PPAAAAAAvv88vvFFFFFFFFvv00++PPAAzz--BBPP11vvFFFFFFFFvv00++77OOOO++++PPOOOO//44999999vv++66vvFFFFFFFFvv00++PP99zz++OO88++PPAAAAvv33PP

```

Run:

```
$ dc < dnr6.short.dc
Do not repeat yourself!

```

# Answer
> 4 votes
# 05AB1E, ~~100~~ ~~58~~ 52 bytes

*-6 bytes thanks to Kevin Cruijssen*

```
„„€€··™™……€€––  ……¹¹‚‚  ……––‚‚))εε##θθáá}}»»……!!θθJJ

```

Try it online!

```
„„€€·              # dictionary string "g do"
     ·             # double (no effect on strings)
      ™            # title case: "G Do"
       ™           # title case again (no effect)
……€€––             # dictionary string "tools not–"
                   # spaces necessary so "–…" isn't parsed as a dictionary word
……¹¹‚‚             # dictionary string "team repeat‚"
                   # spaces necessary again
……––‚‚             # dictionary string "j yourself‚"
)                  # wrap the entire stack in an array
 )                 # and again: [["G Do", "tools not–", "team repeat‚", "j yourself‚"]]
  ε        }       # for each:
   ε      }        #  for each:
    #              #   split on spaces: ["tools", "not–"]
     #             #   and again: [["tools", "not–"]]
      θ            #   get the last element: ["tools", "not–"]
       θ           #   and again: "not–"
        á          #   keep only letters: "not"
         á         #   and again (no effect)
            »      # join the list by newlines, joining sublists by spaces:
                   # "Do not repeat yourself"
             »     # join the stack by newlines, joining lists by spaces (no effect)
……!!               # literal string "…!!"
    θ              # get the last character: "!"
     θ             # and again (no effect)
      J            # join the stack without separators: "Do not repeat yourself!"
       J           # and again (no effect)
                   # implicit output

```

Idempotency rules.

# Answer
> 3 votes
# BotEngine, 6x49=294

```
vv  PP

  !!ee

  ffee

  llee

  eeee

  ssee

  rree

  uuee

  ooee

  yyee

    ee

  ttee

  aaee

  eeee

  ppee

  eeee

  rree

    ee

  ttee

  ooee

  nnee

    ee

  ooee

  DDee

>>  ^^

```

# Answer
> 2 votes
# reticular, noncompeting, 62 bytes

```
2200**UU""DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff!!""oo;;

```

Try it online!

Explanation in parts:

```
2200**
2200    the stack looks like [2 2 0 0]
    *   [2 2 0*0]
     *  [2 2*0*0]
        [2 0]

```

`U` sets the pointer direction to `(2, 0)`, that is, moving `2` x-units and `0` y-units, so it skips every other character, starting with the next `U` being skipped. Then, every other character is recorded, and it is equivalent to:

```
"Do not repeat yourself!"o;

```

which is a simple output program.

## Other

This is competing for WallyWest's JavaScript bounty:

I can prove that, while numbers can be constructed under this restriction, strings cannot. Since no literals can be used, as the placement of any literal-building character would create an empty string:

```
""
''
``

```

Then, only some operator can be used; the only "paired" operators used are:

```
++ -- << >> ** ~~ || && !! ==

```

And none of these can cast numbers/others to strings. So no strings can be outputted.

# Answer
> 2 votes
## Alice, 74 bytes

```
aa00tt,,JJ""DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff!!//@@""ooYY;;tt

```

Try it online!

### Explanation

The first catch is that we need to be able to enter the string, so we want to skip only the first `"`. We do this by jumping onto the first `"` because then the IP will move one cell before looking at the current cell again, so that it's the second `"` which enters string mode. But to be able to jump there, we need `10, 0` on top of the stack, in that order (second, top). This is done with `aa00tt,,`:

```
                          Stack:
aa   Push two 10s.        [... 10 10]
00   Push two 0s.         [... 10 10 0 0]
tt   Decrement twice.     [... 10 10 0 -2]
,    Rotate(-2).          [... 0 10 10]
,    Rotate(10).          [... 0 10 0]

```

This rotation function pops an argument. If that argument is negative, it pushes the value on top of the stack down by that many positions. If the argument is positive, it goes looking for the element that many positions below the top and pulls it up to the top. Note that in the case of `Rotate(10)`, there aren't enough elements on the stack, but there is an implicit infinite amount of zeros at the bottom, which is why a zero ends up on top.

Now we can `J`ump onto the first `"` using these two arguments. The second `"` enters string mode and records all of that `DDoo nnoott...`. When it hits the `/`, the IP is redirected southeast and we enter Ordinal mode. For now on the IP bounces up and down across the three lines (two of which are empty), so it first records three more spaces on lines two and three and then we leave string mode when it hits the `"`. Since we're in Ordinal mode at this time, all the recorded characters are pushed as a single string to the stack (even though we recorded most of them in Cardinal mode), so we end up with this string (note the trailing spaces):

```
DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff!!

```

Now the IP keeps bouncing up and down which means that it executes one command of every other pair, i.e. `Y` and `t`. Then the IP will hit the end of the grid on the second line and start bouncing backwards through the grid. This also switches in which pair of characters the IP hits the first line, so when going back it now executes `;`, `o` and `@`. So ignoring all the spaces and implicit IP redirections, the executed code is `Yt;o@` in Ordinal mode.

The `Y` is the "unzip" command which separates a string into the characters in alternating positions. Since each character is repeated, that really just gives us two copies of the string we're going for, although the first copy has two trailing spaces and the second has one trailing space. `t` splits off that trailing space and `;` discards it. Finally, `o` prints the string and `@` terminates the program.

# Answer
> 2 votes
# Stax, 70 bytes

```
GG11hh::zzaapp..}}..""DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff!!""

```

Run and debug it at staxlang.xyz!

Stax very fortunately has the builtin `::` for every-nth. All I need to is push the string doubled, push 2, and run `::`. Easy, right?

Wrong.

Pushing that string is tricky. The first quotation mark can be doubled by `..""`, which is a length-2 literal for `."` followed by a meaningful quotation mark. Problem is, I see no way to terminate the string (which is necessary, or else the doubled version will be printed) without starting a new one.

The end of the program terminates string literals. If I can put this doubled literal there, perhaps there'll be a nice workaround. To jump somewhere from the end of a program, however, requires `G}`, so at minimum, I'm looking at this:

```
GG [deduplicate] }}""DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff!!""

```

This does... nothing. `G` does not begin a block, so neither will jump to the second `}`. Again, I need to ignore one character: `..}}`. Execution jumps from the first `G` to the second `}`, continues to the end, jumps back to the second `G` and from there to the second `}`, and continues once more to the end before resuming at the start of the `[deduplicate]` section with the doubled string atop the stack.

Deduplication is simple. `11hh` pushed eleven and halves it twice, rounding down both times and yielding two, and `::` will then get us the output we need.

```
GG11hh::..}}..""DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff!!""

```

Uh-oh. This prints nothing. There are two problems here: first, that `..}` means the string `.}` will be atop the stack at the end of the program, and second, Stax's ordinary implicit output is now disabled!

The worse issue is the output. When a Stax program terminates gracefully without printing anything, the top of the stack will be implicitly printed. But we haven't printed anything...? Ah, but we have. Unterminated string literals are printed rather than pushed, and even those two empty strings (from the unmatched `"` at the end), despite being empty, are enough to trip this check. Any printing must be done by hand.

We'll need either `pp` or `PP`, and in this instance, ignoring the first through `..pp` is unacceptable, as it will print the string `.p`. That means we need our desired output either alone on the stack or in the top two along with an empty string. This latter is accomplished by pushing two empty strings (`zz`) and rotating the top three items twice (`aa`) before printing.

Once that's done, we have a stack four strings tall. A fifth, `.}`, is then pushed before the program exits gracefully; at this point, the lack of implicit output becomes a blessing as well as a curse, as nothing extra will now be printed!

---
Tags: code-golf, kolmogorov-complexity, restricted-source
---