title: Uncollapse digits

text:
# Question
Title: Uncollapse digits
# Task

Given a string of English names of digits “collapsed” together, like this:

```
zeronineoneoneeighttwoseventhreesixfourtwofive

```

Split the string back into digits:

```
zero nine one one eight two seven three six four two five

```

# Rules

* The input is always a string. It always consists of one or more lowercase English digit names, collapsed together, and nothing else.

+ The English digit names are `zero one two three four five six seven eight nine`.
* The output may be a list of strings, or a new string where the digits are delimited by non-alphabetic, non-empty strings. (Your output may also *optionally* have such strings at the beginning or end, and the delimiters need not be consistent. So even something like `{{ zero0one$$two );` is a valid (if absurd) answer for `zeroonetwo`.)
* The shortest answer in bytes wins.

# Test cases

```
three -> three
eightsix -> eight six
fivefourseven -> five four seven
ninethreesixthree -> nine three six three
foursixeighttwofive -> four six eight two five
fivethreefivesixthreenineonesevenoneeight -> five three five six three nine one seven one eight
threesevensevensixninenineninefiveeighttwofiveeightsixthreeeight -> three seven seven six nine nine nine five eight two five eight six three eight
zeroonetwothreefourfivesixseveneightnine -> zero one two three four five six seven eight nine

```

# Answer
> 31 votes
# Retina, 20 bytes

```
!`..[eox]|[tse]?....

```

Try it online!

# Answer
> 17 votes
# C (gcc), ~~89 80 76 75 72 71 70~~ 69 bytes

```
f(char*s){*s&&f(s+printf(" %.*s",""[(*s^s[2])%12],s)-1);}

```

Try it online!

(89) Credit to gastropner for the XOR hash.
(76) Credit to Toby Speight for the idea of using 1st and 3rd.
(75) Credit to Michael Dorgan for `'0'``48`.
(72) Credit to Michael Dorgan and Lynn for literals with control characters.
(69) Credit to Lynn for `x?y:0``x&&y`

```
f (char *s) {        /* K&R style implicit return type. s is the input. */
    *s&&f(           /* Recurse while there is input. */
        s+printf(    /* printf returns the number of characters emitted. */
            " %.*s", /* Prefix each digit string with a space. Limit
                      * how many bytes from the string to print out. */
            ""
                     /* Magic hash table, where the value represents
                      * the length of the digit string. The string
                      * is logically equivalent to
                      * "\04\01\05\03\04\05\05\04\04\01\03\03" */
            [(*s^s[2])%12],
                     /* The XOR hash (mod 12) */
            s)       /* The current digit. */
            -1);}    /* Subtract 1 for the space. */
```

# Answer
> 13 votes
# Python 2, 50 bytes

```
import re
re.compile('..[eox]|[tse]?....').findall

```

Try it online!

-3 thanks to Lynn.
-4 thanks to Uriel's answer's regex.

# Answer
> 9 votes
# Befunge, ~~87~~ ~~85~~ ~~81~~ 76 bytes

```
<*"h"%*:"h"$_02g-v1$,*<v%*93,:_@#`0:~
"@{&ruX;\"00^ !: _>_48^>+:"yp!"*+%02p0

```

Try it online!

Befunge doesn't have any string manipulation instructions, so what we do is create a kind of hash of the last three characters encountered, as we're processing them.

This hash is essentially a three digit, base-104 number. Every time a new character is read, we mod the hash with 1042 to get rid of the oldest character, multiply it by 104 to make space for the new character, then add the ASCII value of the new character mod 27 (to make sure it doesn't overflow).

For comparison purposes, we take this value mod 3817, write it into memory (thus truncating it to 8 bits), which results in smaller numbers that are easier for Befunge to handle. The hashes we then have to compare against are 0, 38, 59, 64, 88, 92, 114, 117, and 123. If it matches any of those, we know we've encountered a character sequence that marks the end of a number, so we output an additional space and reset the hash to zero.

If you're wondering why base 104, or why mod 3817, those values were carefully chosen so that the hash list we needed to compare against could be represented in as few bytes as possible.

# Answer
> 6 votes
# C (gcc), ~~179~~ ~~159~~ ~~146~~ ~~139~~ ~~137~~ ~~116~~ ~~107~~ ~~103~~ 102 bytes

**Edit 1:** (Added suggestions from **Mr. Xcoder** \- thanks! - My macro version was same size as yours, but I like yours better.)

**Edit 2:** Changed char individual compares to calls to `strchr()`

**Edit 3:** K&R's the var declarations (Eww!)

**Edit 4:** When 1 macro is not enough...

**Edit 5:** Redone with new algorithm suggested above. Thanks to **James Holderness** for this great idea!

**Edit 6:** Removed 0 set as it seems to go there automatically - Master level code golf techniques used (commas, printf trick, etc.) - thanks **gastropner**!

**Edit 7:** Use memchr and fixed a bug pointed out by **James Holderness**.

**Edit 7:** Use `&&` on final check to replace `?` \- thanks **jxh**.

```
c,h;f(char*s){while(c=*s++)putchar(c),h=h%10816*104+c%27,memchr("&;@X\\ru{",h%3817,9)&&putchar(h=32);}

```

Try it online!

Non-golfed (Which is still very golfy honestly...)

```

int c;
int h;
void f(char*s)
{
    while(c=*s++)
        putchar(c),
        h=h%10816*104+c%27,
        memchr("&;@X\\ru{",h%3817,9)?putchar(h=32):1;
}

```

Old, straight forward grep-esqe solution:

```
#define p putchar
#define q c=*s++
c,x;f(char*s){while(q){p(c);x=strchr("tse",c);p(q);p(q);if(!strchr("eox",c)){p(q);if(x)p(q);}p(' ');}}

```

Old, cleaner version.

```
// Above code makes a macro of putchar() call.

void f(char *s)
{
    char c;
    while(c = *s++)
    {
        putchar(c);
        int x = strchr("tse", c);

        putchar(*s++);
        putchar(c=*s++);

        if(!strchr("eox", c))
        {
            putchar(*s++);
            if(x)
            {
                putchar(*s++);
            }
        }
        putchar(' ');
    }
}

```

Try it online!

# Answer
> 6 votes
# Java (OpenJDK 8), ~~55~~ ~~46~~ 43 bytes

*Saving 9 bytes thanks to Forty3/FrownyFrog*

*Saving 3 bytes thanks to Titus*

```
s->s.replaceAll("one|tw|th|f|z|s|.i"," $0")

```

Try it online!

edit: Thank you for the welcome and explanation of lambdas!

# Answer
> 5 votes
# Retina, ~~24~~ 23 bytes

```
!`..[eox]|[fnz]...|.{5}

```

Try it online! Edit: Saved 1 byte thanks to @FrownyFrog.

# Answer
> 5 votes
# JavaScript, 66 57 52 44 41 bytes

`s=>s.replace(/one|t[wh]|.i|[fsz]/g," $&")`

Pretty naive, but it works.

Nice catch by FrownyFrog to use 2 chars .. except for "one" which a pure 2 char check might mess up zeronine. Edit: the single `f` and `s` were good catches by FrownyFrog that I overlooked my first two golfs.

Thanks, Neil, for the suggestion of an unnamed lambda and being able to use a single char for `z` gets down to 52.

Titus comes up with a smaller RegEx. I feel we are heading toward Uriel's regex eventually.

# Answer
> 5 votes
# C, ~~103~~ 99 bytes

```
char*r="f.tzuonresn.xgv";f(char*s){*s&&f(s+printf("%.*s ",(strrchr(r,s[2])-strchr(r,*s))%10,s)-1);}

```

This works for any character encoding (including awkward ones like EBCDIC), because it doesn't use the numeric value of the input characters. Instead, it locates the first and third letters in a magic string. The distance between these indicates how many letters to advance with each print.

## Test program

```
#include <stdio.h>
int main(int argc, char **argv)
{
    for (int i = 1;  i < argc;  ++i) {
        f(argv[i]);
        puts("");
    }
}

```

# Answer
> 4 votes
# , ~~37~~ 35 bytes

```
rplc'twthsiseeinionzef'(;LF&,)\~_2:

```

Try it online!

# Answer
> 4 votes
# C (gcc), ~~106 bytes~~ ~~104~~ 102 bytes

-2 bytes thanks to @jxh -2 bytes thanks to ceilingcat

```
c;f(char*s){for(char*t=" $&=B*,29/?";*s;)for(c=4+(index(t,(*s^s[1])+35)-t)/4;c--;)putchar(c?*s++:32);}

```

Try it online!

XOR is truly our greatest ally.

# Answer
> 4 votes
# Z80 Assembly, 46 45 bytes

```
; HL is the address of a zero-terminated input string
; DE is the address of the output buffer

Match5: ldi                                 ; copy remaining characters
Match4: ldi
Match3: ld a,32 : ld (de),a : inc de        ; and add space after a matched word.

Uncollapse:

        ld a,(hl) : ldi : or a : ret z      ; copy first byte (finish if it was zero)
        ex af,af'                           ; and save its value for later.

        ldi : ld a,(hl) : ldi               ; copy second and third bytes

        cp 'e' : jr z,Match3                ; is the third letter 'e' or 'o' or 'x'?
        cp 'o' : jr z,Match3
        cp 'x' : jr z,Match3

        ex af,af'                           ; now look at the first letter

        cp 'e' : jr z,Match5                ; is it 't' or 's' or 'e'?
        sub 's' : jr z,Match5
        dec a : jr z,Match5
        jr Match4

```

(It was fun to adapt the Uriel's cool regex to a regex-unfriendly environment).

# Answer
> 4 votes
# Jelly,  ~~23~~  21 bytes

```
ḣ3OP%953%7%3+3ɓḣṄȧṫḊÇ

```

A full program printing line-feed separated output. Note: once it's done it repeatedly prints empty lines "forever" (until a huge recursion limit or a seg-fault)

**Try it online!** (TIO output is accumulated, a local implementation will print line by line)

### How?

Starting with a list of characters, the program repeatedly:

1. finds the length of the first word of the list of characters using some ordinal mathematics;
2. prints the word plus a linefeed; and
3. removes the word from the head of the list of characters

The length of the first word is decided by inspecting the first three characters of the current list of characters (necessarily part of the first word). The program converts these to ordinals, multiplies them together, modulos the result by 953, modulos that by seven, modulos that by three and adds three:

```
word   head3  ordinals       product  %953  %7  %3  +3 (=len(word))
zero   zer    [122,101,114]  1404708   939   1   1   4
two    two    [111,110,101]  1233210    28   0   0   3
one    one    [116,119,111]  1532244   773   3   0   3
three  thr    [116,104,114]  1375296   117   5   2   5
four   fou    [102,111,117]  1324674     4   4   1   4
five   fiv    [102,105,118]  1263780   102   4   1   4
six    six    [115,105,120]  1449000   440   6   0   3
seven  sev    [115,101,118]  1370570   156   2   2   5
eight  eig    [101,105,103]  1092315   177   2   2   5
nine   nin    [110,105,110]  1270500   151   4   1   4

```

```
ḣ3OP%953%7%3+3ɓḣṄȧṫḊÇ - Main link, list of characters           e.g. "fiveeight..."
ḣ3              - head to index three                                "fiv"
  O             - ordinals                                           [102,105,118]
   P            - product                                            1263780
    %953        - modulo by 953                                      102
        %7      - modulo by seven                                    4
          %3    - modulo by three                                    1
            +3  - add three                                          4

              ɓ - dyadic chain separation swapping arguments...
... ḣṄȧṫḊÇ ...
    ḣ         - head to index                                        "five"
     Ṅ        - print the result plus a line-feed and yield the result
       ṫ      - tail from index                                      "eeight..."
      ȧ       - and (non-vectorising)                                "eeight..."
        Ḋ     - dequeue                                               "eight..."
         Ç    - call the last link (Main*) as a monad with this as input
              -       * since it's the only link and link indexing is modular.

```

# Answer
> 3 votes
# Retina, 28 bytes

```
t[ewh]|[zfs]|(ni|o)ne|ei
 $&

```

Try it online!

# Answer
> 3 votes
# Pyth, ~~35 27~~ 23 bytes

Saved a lot of bytes by porting Uriel's approach.

```
:Q"..[eox]|[tse]?...."1

```

Try it here! Initial approach.

# Answer
> 3 votes
# Pip, 27 bytes

```
aR`[zfs]|one|[ent][iwh]`s._

```

Takes input as a command-line argument. Try it online!

Simple regex replacement, inserts a space before each match of `[zfs]|one|[ent][iwh]`.

---

Jumping on the bandwagon of ~~stealing~~ borrowing Uriel's regex gives **23 bytes** (with `-s` flag):

```
a@`..[eox]|[tse]?....`

```

# Answer
> 3 votes
# C ~~168~~ ,~~145~~,~~144~~,141 bytes

EDIT: Tried init 'i' to 1 like so

> a,b;main(i)

To get rid of leading whitespace,
but it breaks on input starting with three, seven or eight

**141**

```
#define s|a%1000==
a,i;main(b){for(;~scanf("%c",&b);printf(" %c"+!!i,b),a|=b%32<<5*i++)if(i>4|a%100==83 s 138 s 116 s 814 s 662 s 478)a=i=0;}

```

Try it online

**144**

```
a,i;main(b){for(;~(b=getchar());printf(" %c"+!!i,b),a=a*21+b-100,++i)if(i>4|a==204488|a==5062|a==7466|a==23744|a==21106|a==6740|a==95026)a=i=0;}

```

Try it online

**168**

```
i,a;main(b){for(;~scanf("%c",&b);printf(" %c"+!!i,b),a|=b<<8*i++)if(i>4|a==1869768058|a==6647407|a==7305076|a==1920298854|a==1702259046|a==7891315|a==1701734766)a=i=0;}

```

Try it online!

Ungolfed

```
i,a;main(b){
for(;~scanf("%c",&b); // for every char of input
printf(" %c"+!!i,b), // print whitespace if i==0 , + char
a|=b<<8*i++ // add char to a for test
)
if(
i>4| // three seven eight
a==1869768058|      // zero
a==6647407|        // one
a==7305076|       // two
a==1920298854|   //four
a==1702259046|  //five
a==7891315|    //six
a==1701734766 //nine
) a=i=0; //reset i and a
}

```

int constants gets unnecessary large by shifting a\<\<8
but in case you can compare to strings somehow it should be the most natural

**146** Using string comparison

```
#define s|a==*(int*)
a,b;main(i){for(;~(b=getchar());printf(" %c"+!!i,b),a|=b<<8*i++)if(i>4 s"zero"s"one"s"two"s"four"s"five"s"six"s"nine")a=i=0;}

```

Using String comparison

Obfuscated

```
#define F(x)if(scanf(#x+B,&A)>0){printf(#x,&A);continue;}
B;A;main(i){for(;i;){B=1;F(\40e%4s)F(\40th%3s)F(\40se%3s)F(\40o%2s)B=2;F(\40tw%1s)F(\40si%1s)B=1;F(\40%4s)i=0;}}

```

# Answer
> 3 votes
# Python 3, no regex,  ~~83 68 65~~  63 bytes

-15 thanks to Lynn (refactor into a single function)
-3 more thanks to Lynn (avoid indexing into a list with more arithmetic)
...leading to another save of 2 bytes (avoiding parenthesis with negative modulos) :)

```
def f(s):h=ord(s[0])*ord(s[1])%83%-7%-3+5;print(s[:h]);f(s[h:])

```

A function which prints the words separated by newlines and then raises an `IndexError`.

**Try it online!** (suppresses the exceptions to allow multiple runs within the test-suite)

# Answer
> 2 votes
# Jelly, 44 bytes

```
Ṛ¹Ƥz⁶ZUwÐ€“¢¤Ƙƒ⁺6j¹;Ċ-ḶṃżṃgɼṘƑUẏ{»Ḳ¤$€Ẏḟ1Ṭœṗ

```

Try it online!

# Answer
> 2 votes
Quite long one. You are welcome to golf it down.

# , 109 bytes

```
function(x)for(i in utf8ToInt(x)){F=F+i;cat(intToUtf8(i),if(F%in%c(322,340,346,426,444,448,529,536,545))F=0)}

```

Try it online!

# Answer
> 2 votes
# Haskell, 81 bytes

```
f[c]=[c]
f(h:t)=[' '|s<-words"z one tw th f s ei ni",and$zipWith(==)s$h:t]++h:f t

```

Try it online!

**Explanation:**

```
f(h:t)=                      h:f t -- recurse over input string
   [' '|s<-               ]++      -- and add a space for each string s
      words"z one tw th f s ei ni" -- from the list ["z","one","tw","th","f","s","ei","ni"]
      ,and$zipWith(==)s$h:t        -- which is a prefix of the current string

```

# Answer
> 2 votes
# Python 3 (no regex), 85 bytes

```
i=3
while i<len(s):
	if s[i-3:i]in'ineiveroneghtwoureesixven':s=s[:i]+' '+s[i:]
	i+=1

```

Try it online!

# Answer
> 2 votes
# Excel, 181 bytes

```
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"z"," z"),"on"," on"),"tw"," tw"),"th"," th"),"f"," f"),"s"," s"),"ei"," ei"),"ni"," ni")

```

Places a space in front of: `z`, `on`, `tw`, `th`, `f`, `s`, `ei`, `ni`

# Answer
> 1 votes
# Jelly, ~~40~~ 39 bytes

```
“¢¤Ƙƒ⁺6j¹;Ċ-ḶṃżṃgɼṘƑUẏ{»Ḳe€€@ŒṖẠ€TḢịŒṖK

```

Try it online!

## How it works

```
“¢¤Ƙƒ⁺6j¹;Ċ-ḶṃżṃgɼṘƑUẏ{»Ḳe€€@ŒṖẠ€TḢịŒṖK
“¢¤Ƙƒ⁺6j¹;Ċ-ḶṃżṃgɼṘƑUẏ{»                 = the compressed string of the digit names
                        Ḳ                = split at spaces
                         e€€@ŒṖ          = check whether each member of each partition of the argument is a digit.
                               Ạ€        = A function that checks whether all values of an array are true, applied to each element.
                                 T       = Finds the index of each truthy element
                                  Ḣ      = Grab the first element, since we have a singleton array
                                    ịŒṖ  = The previous command gives us the index, partition that splits the input into digits. This undoes it and gives us the partition.
                                       K = Join the array of digits with spaces

```

# Answer
> 1 votes
# QuadS, ~~21~~ 20 bytes

```
..[eox]|[tse]?....
&

```

Try it online!

This is a port of my retina answer.

# Answer
> 1 votes
# APL (Dyalog Unicode), 25 bytes

```
'..[eox]|[tse]?....'⎕S'&'

```

Try it online!

# Answer
> 1 votes
# Scala 3, 45 bytes

Use Regular Expression (`scala.util.matching.Regex`)

---

Golfed version. Attempt This Online!

```
"""..[eox]|[tse]?....""".r.findAllIn(_).toSeq

```

Ungolfed version. Attempt This Online!

```
import scala.util.matching.Regex

object Main {
  def main(args: Array[String]): Unit = {
    val pattern: Regex = """..[eox]|[tse]?....""".r

    val input = "threesevensevensixninenineninefiveeighttwofiveeightsixthreeeight"
    val matches = pattern.findAllIn(input).toList

    println(matches.mkString(", "))
  }
}

```

# Answer
> 0 votes
# Jelly, 36 bytes

```
œṣj⁶;$}
W;“€ɗİẒmṫṃ¦¦ạỊɦ⁼Fḷeṭḷa»s2¤ç/

```

Try it online!

Algorithm:

```
for x in ['ze', 'ni', 'on', 'tw', 'th', ...]:
    replace x in input by space+x

```

I bet we can do even better.

# Answer
> 0 votes
# Mathematica, 125 bytes

```
(s=#;While[StringLength@s>2,t=1;a="";While[FreeQ[IntegerName/@0~Range~9,a],a=s~StringTake~t++];Print@a;s=StringDrop[s,t-1]])&

```

Try it online!

TIO outputs an error message about "CountryData"(???)
I don't know why this happens, but eveything works fine on Mathematica

# Answer
> 0 votes
# Perl 6,  ~~42~~  30 bytes

```
*.comb(/<{(0..9).Str.uninames.lc.words}>/)

```

Test it

```
{m:g/..<[eox]>||<[tse]>?..../}

```

Test it
(Translated from other answers)

# Answer
> 0 votes
# q/kdb+, ~~59~~ 51 bytes

**Solution:**

```
{asc[raze x ss/:string`z`one`tw`th`f`s`ei`ni]cut x}

```

**Example:**

```
q){asc[raze x ss/:string`z`one`tw`th`f`s`ei`ni]cut x}"threesevensevensixninenineninefiveeighttwofiveeightsixthreeeight"
"three"
"seven"
"seven"
"six"
"nine"
"nine"
"nine"
"five"
"eight"
"two"
"five"
"eight"
"six"
"three"
"eight"

```

**Explanation:**

Quick solution, probably better and more golfable approaches.

```
{asc[raze x ss/:string`z`one`tw`th`f`s`ei`ni]cut x} / ungolfed solution
{                                                 } / lambda with implicit x as input
                                             cut x  / cut x at indices given by left
 asc[                                       ]       / sort ascending
                string`z`one`tw`th`f`s`ei`ni        / string list ("z","one",...)
          x ss/:                                    / string-search left with each right
     raze                                           / reduce down list

```

**Notes:**

46 bytes with some simple golfing, replacing q calls with k ones, but still a hefty solution.

`asc[(,/)x ss/:($)`z`one`tw`th`f`s`ei`ni]cut x:`

# Answer
> 0 votes
# GNU sed, 35 bytes

(including +1 for the `-r` flag)

```
s/([ots]|[zfn].|(se|th|ei).)../ &/g

```

Just a simple regexp replacement.

# Answer
> 0 votes
# Ruby, 33 bytes

```
->s{s.scan(/..[eox]|[tse]?..../)}

```

Try it online!

(Everybody else is doing it, so why can't we?)

# Answer
> 0 votes
# Perl5, 26 bytes

```
echo zeronineoneoneeighttwoseventhreesixfourtwofive \
| perl -ple 's/..[eox]|[tse]?..../$& /g'

```

Or just the program:

```
s/..[eox]|[tse]?..../$& /g

```

# Answer
> 0 votes
# Deorst, 22 bytes

```
'..[eox]|[tse]?....'gf

```

Try it online!

Of course, this uses the regex found by Uriel. Although, it’s great when Deorst beats Pyth and Jelly :P

# Answer
> 0 votes
# Matlab, 432 bytes

A long attempt.

```
s=char(input('','s'));o=[];while length(s)>0;switch s(1:2);case'ze';o=[o,' ',s(1:4)];s(1:4)=[];case'on';o=[o,' ',s(1:3)];s(1:3)=[];case'tw';o=[o,' ',s(1:3)];s(1:3)=[];case 'th';o=[o,' ',s(1:5)];s(1:5)=[];case'fo';o=[o,' ',s(1:4)];s(1:4)=[];case'fi';o=[o,' ',s(1:4)];s(1:4)=[];case 'si';o=[o,' ',s(1:3)];s(1:3)=[];case'se';o=[o,' ',s(1:5)];s(1:5)=[];case 'ei';o=[o,' ',s(1:5)];s(1:5)=[];otherwise;o=[o,' ',s(1:4)];s(1:4)=[];end;end;o

```

ungolfed:

```
s=char(input('','s'))
o=[]
while length(s)>0
switch s(1:2)
    case 'ze'
        o=[o,' ',s(1:4)]
        s(1:4)=[]
    case 'on'
        o=[o,' ',s(1:3)]
        s(1:3)=[]
    case 'tw'
        o=[o,' ',s(1:3)]
        s(1:3)=[]
    case 'th'
        o=[o,' ',s(1:5)]
        s(1:5)=[]
    case 'fo'
        o=[o,' ',s(1:4)]
        s(1:4)=[]
    case 'fi'
        o=[o,' ',s(1:4)]
        s(1:4)=[]
    case 'si'
        o=[o,' ',s(1:3)]
        s(1:3)=[]
    case 'se'
        o=[o,' ',s(1:5)]
        s(1:5)=[]
    case 'ei'
        o=[o,' ',s(1:5)]
        s(1:5)=[]
    otherwise
        o=[o,' ',s(1:4)]
        s(1:4)=[]
end
end
o

```

# Answer
> 0 votes
# Ruby, 77 bytes

```
puts gets.gsub(/(one|two|three|four|five|six|seven|eight|nine)/,' \1 ').strip

```

Try it online!

# Answer
> 0 votes
# Swift 5.9, 76 bytes

```
let f={($0+"").replacing(#/one|t[wh]|.i|[fsz]/#){" "+$0.output}.dropFirst()}

```

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


# Question
Title: How quickly can you type this unary string?
If I want to type the string `aaa`, the least keystrokes I can type it in is 3: `a a a`. But if I want to type the string `aaaaaa`, I can do it in 5: `a a a ctrl-c ctrl-v`, where the `ctrl-c` refers to copying `aaa` and the `ctrl-v` refers to pasting it.

Specifically, starting with an empty "buffer" and an empty "clipboard":

* The keystroke `a` appends an `a` to the buffer.
* `ctrl-c` takes some substring of the buffer and stores it into the clipboard. I'll notate it as `ctrl-c(5)` or similar to refer to 5 characters being stored. Only one string can be stored into the clipboard, and storing overwrites previous content.
* `ctrl-v` appends the clipboard to the buffer.

Each of these counts as one keystroke.

With a larger example, the least keystrokes 17 `a`s can be typed in is 8:

```
a a a ctrl-c(3) ctrl-v ctrl-v ctrl-c(8) ctrl-v

```

Your challenge is to, given a number `n`, return the number of keystrokes required to type `n` `a`s. This is , shortest wins!

## Testcases

These are done by hand, so tell me if any of these are wrong. Also, this doesn't appear to be on OEIS. I've written some not-quite-functional python code to find all possible outputs for a given length.

The first 30 terms of the sequence are:

```
1,2,3,4,5,5,6,6,6,7,7,7,8,8,8,8,8,8,9,9,9,9,9,9,10,9,10,10,10

```

And some more specific ones, with examples:

```
11 -> 7 (a a a ctrl-c(3) ctrl-v ctrl-c(5) ctrl-v)
17 -> 8 (a a a ctrl-c(3) ctrl-v ctrl-v ctrl-c(8) ctrl-v)
25 -> 9 (a a a ctrl-c(3) ctrl-v ctrl-v ctrl-c(8) ctrl-v ctrl-v, the python code doesn't find this one)
75 -> 12 (a a a ctrl-c(3) ctrl-v ctrl-v ctrl-c(9) ctrl-v ctrl-v ctrl-c(24) ctrl-v ctrl-v, python code also misses this one)

```

# Answer
> 8 votes
# JavaScript (Node.js), 47 bytes

* -1 by Arnauld.

```
f=x=>x<6?x:Math.min(f(x+1>>1)+2,f(x-=x/3<<1)+3)

```

Try it online!

---

# Python 2, 49 bytes

```
f=lambda x:x*(x<6)or min(f(x-x/2)+2,f(x-x/3*2)+3)

```

Try it online!

~~I don't really ensure this function is correct. But it at least pass all testcases given.~~

After I ask this solution on Math SE, caduk had provided a nice prove to it. You may read the prove by caduk on Math SE.

Anyway, the formula is

$$ f(x)= \begin{cases} n & n\<6 \\ \min \left\\{f\left(n-\left\lfloor\frac{n}{2}\right\rfloor\right)+2, f\left(n-2\left\lfloor\frac{n}{3}\right\rfloor\right)+3 \right\\} & \text{otherwise} \end{cases} $$

# Answer
> 3 votes
# JavaScript (Node.js), 68 bytes

```
f=(n,m,i=n>>1)=>i?Math.min(f(n-i,i)-~(i!=m),f(n,m,i-1),f(n-1,m)+1):n

```

Try it online!

# Answer
> 3 votes
# Charcoal, ~~51~~ 38 bytes

```
⊞υ⟦⁰⟧ＦＮ⊞υＥ⁺²ι⌊Ｅ⮌υ⌊Ｅμ⁺ξ⁺∨⁼π⊕ν⊕ν¬⁼πκＩ⌊⊟υ

```

Try it online! Link is to verbose version of code. Explanation: Uses dynamic programming on the basic recurrence relation, which may be equivalent to @l4m2's approach, but I can't read it.

```
⊞υ⟦⁰⟧

```

Start with `0` keystrokes to type `0` `a`s.

```
ＦＮ

```

Loop over all numbers up to `n`.

```
⊞υＥ⁺²ι⌊Ｅ⮌υ⌊Ｅμ⁺ξ⁺∨⁼π⊕ν⊕ν¬⁼πκ

```

Loop over all clipboard sizes up to `n` and calculate the minimum number of keystrokes needed for the current number while finishing with that clipboard size. All previous entries are considered; `1` is added to the entry if it has a different clipboard size, as that means another `^C` is needed, plus the number of extra `a`s is added, unless the clipboard is of exactly the right size, in which case `1` is added, as in that case only a `^V` is needed. (The values where more than one `a` is needed are unnecessary but it's golfier to calculate and discard them.)

```
Ｉ⌊⊟υ

```

Output the minimum number of keystrokes needed to output `n` in unary.

A port of @tsh's formula using dynamic programming takes 33 bytes:

```
Ｆ⊕Ｎ⊞υ⎇‹ι⁶ι⌊Ｅ²⁺⁺²κ§υ⁻ι×⊕κ÷ι⁺²κＩ⌊⊟υ

```

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

# Answer
> 2 votes
# Swift 5.9, 48 bytes

```
let f={x in x<6 ?x:2+min(f(x-x/2),1+f(x-x/3*2))}

```

A direct port of @tsh's Python 2 answer, because I don't know how else to do this concisely.

# Answer
> 2 votes
# Python3, 327 bytes

```
R=range
def f(n):
 q,s,r=[(0,0)],[],[]
 for a,c in q:
  if a==n:r+=[c];continue
  if r and c>=min(r):continue
  if a<3:q+=[(a+1,c+1)]
  else:
   U=[(a+1,c+1)]
   for i in R(3,min(a,n-a)+1):
    for j in R(1,(n-a)//i+1):U+=[(a+i*j,c+1+j)]
   for A,B in U:
    if all(k<A or K>B for k,K in s):q+=[(A,B)];s+=[(A,B)]
 return min(r)

```

Try it online!

# Answer
> 1 votes
# Ruby, 42 bytes

```
f=->x{x<6?x:2-[-f[x-x/2],~f[x-x/3*2]].max}

```

Try it online!

Not very original, basically a port of tsh's answer.

# Answer
> 1 votes
# Scala 3, 64 bytes

A direct port of @tsh's Python 2 answer.

---

```
def f(x:Int):Int=if(x<6)x else 2+Math.min(f(x-x/2),1+f(x-x/3*2))

```

Attempt This Online!

---
Tags: code-golf, math, sequence, integer
---


title: Evaluate Ternary Logic

text:
# Question
Title: Evaluate Ternary Logic
# Objective

Given an expression involving ternary values, evaluate it into a ternary value.

# Ternary Values

The three truth values in question are the values of Haskell's `Ordering`, namely `LT`, `EQ`, and `GT`. They stand for "less-than", "equal-to", and "greater-than", respectively. Furthermore, they themselves have an order; `LT` is the least, and `GT` is the greatest.

# Operators

The binary operators for the ternary values are Haskell's `min`, `max`, `compare`, and `(<>)`, all instantiated for `Ordering`. They're defined as:

```
min|LT EQ GT
---|--------
LT |LT LT LT
EQ |LT EQ EQ
GT |LT EQ GT

```

```
max|LT EQ GT
---|--------
LT |LT EQ GT
EQ |EQ EQ GT
GT |GT GT GT

```

```
compare|LT EQ GT
-------|--------
  LT   |EQ LT LT
  EQ   |GT EQ LT
  GT   |GT GT EQ

```

```
(<>)|LT EQ GT
----|--------
 LT |LT LT LT
 EQ |LT EQ GT
 GT |GT GT GT

```

# I/O Format

Flexible. You may represent the values and the operators in an arbitrary way. In particular, the expression may be in Polish notation.

# Examples

Here, the shorthands are `T` for `LT`, `0` for `EQ`, `1` for `GT`, `&` for `min`, `|` for `max`, `c` for `compare`, and `s` for `(<>)`. The expressions are in Polish notation.

```
Expression, Evaluation

c01, T
sT1, T
|0&1T, 0
|&1T0, 0
s0s00, 0
s0s01, 1
sTcTT, T
cs10T, 1
cs01&|01T, 1

```

# Answer
> 7 votes
# Vyxal 3, 1 byte

```
Ė

```

Try it Online!

Accepts input in reverse polish notation with `LT` represented by `1N`, `EQ` represented by `0`, and `GT` represented by `1`. `min` is `g`, `max` is `G`, `compare` is , and `<>` is .

These operators are, respectively, `min`, `max`, `difference` into `sign`, and `logical or`, which is all these really are when we represent them like such.

---

As much as this feels like cheating, if I were required to follow the test cases' format I think the easiest method is probably to convert from prefix to postfix notation, map the characters to the above strings, and then evaluate, which is really not any more interesting in my opinion.

That said, here's a method without evaluate, though I honestly find it less clever because it's just trivial implementation. It takes the input like in the test cases but still in reverse polish notation because inverting it is already a different challenge.

### Vyxal 3, 59 bytes

```
Ṛ0Ḣ&Ṛ₳:"01T"$c["01"$Ḟ&|$ṫ$ṫ$^"&|cs"$ḞᵈgᵈGᵉ-±ᵈ∨;JJiĖ&)"01T"i

```

Try it Online! (link is to literate version)

Here's a brief explanation of how this works:

```
Ṛ0Ḣ&Ṛ                  sets up [[], ...] containing the input
₳ ... )                reduce (so each time we take the list and one character)
  :"01T"$c             check if the character is one of 0, 1, or T
  [ ... | ...          IF-ELSE
    "01"$Ḟ&            if so, then just append it (-1 for T)
    ...                else:
      $ṫ$ṫ$^           pop the last two off the list and reorder the stack
      "&|cs"$Ḟ         find the character in "&|cs"
      ᵈgᵈGᵉ-±ᵈ∨;JJiĖ&  index into a list of the aforementioned functions
"01T"i                 finally, index into "01T" to format the output

```

Although this uses `Ė`, that's just to execute the function. It isn't being used as `eval` here; Vyxal just overloads that character to mean many things.

# Answer
> 4 votes
# Python 2, 52 bytes

```
f=lambda s:s.pop(0)(f(s),f(s))if 1<s[0]else s.pop(0)

```

Attempt This Online!

Takes input in Polish notation with the following mapping:

```
LT -> -1
EQ -> 0
GT -> 1

min -> min
max -> max
compare -> cmp
(<>) -> int.__or__

```

# Answer
> 4 votes
# Retina 0.8.2, 88 bytes

```
{`(?=(S.?L|S.?E?|B.?G|B.?E?|OE?.|CE.|CLG|CGL)(?<=(.))).[GEL]{2}
$2
CGE
L
CLE
G
CLL|CGG
E

```

Try it online! Link includes test cases. Key: `L` \- `LT`; `E` \- `EQ`; `G` \- `GT`; `S` \- `min`; `B` \- `max`; `C` \- `compare`, `O` \- `(<>)`. Note that `C`s operands are reversed (test cases have been adapted accordingly). Explanation:

```
{`

```

Repeat until no more operators can be reduced.

```
(?=(S.?L|S.?E?|B.?G|B.?E?|OE?.|CE.|CLG|CGL)(?<=(.))).[GEL]{2}
$2

```

Look for an operator followed by two operands, where one of the operands is also the result, in which case replace the trio with that operand.

```
CGE
L
CLE
G
CLL|CGG
E

```

Replace trios where the result does not match any of the operands.

* `S.?L`: `min` when at least one operand is `L` is that operand, otherwise
* `S.?E?`: `min` of two non-`L` operands is `E` if it is either operand otherwise it is an operand (they are both `G` at this point)
* `B.?G`: `max` when at least one operand is `G` is that operand, otherwise
* `B.?E?`: `max` of two non-`G` operands is `E` if it is either operand otherwise it is an operand (they are both `L` at this point)
* `OE?.`: `(<>)` of `E` with anything is the second operand otherwise it is the first operand
* `CE.`: Reversed compare of `E` with anything is the second operand
* `CLG`: Reversed compare of `L` with `G` is `G`
* `CGL`: Reversed compare of `G` with `L` is `L`

# Answer
> 2 votes
# JavaScript (Node.js), 103 bytes

```
x=>x.map(i=>a.push(i<2?i:[p=>p<q?p:q,p=>p<q?q:p,p=>(p>q)-(q>p),p=>p||q][i-2](a.pop(q=a.pop()))),a=[])|a

```

Try it online!

const `SSS = 5` mean `<>`

Reverse Polish Notation

---

# JavaScript (Node.js), 64 bytes

-2B from tsh

```
eval
with(Math)M=max,m=min,T=-1,S=(a,b)=>a||b,C=(a,b)=>sign(a-b)

```

Try it online!

# Answer
> 2 votes
# APL(Dyalog Unicode), 1 byte SBCS

Try it on APLgolf!

Takes input as a parenthesized infix expression. This does feel a bit like cheating...

Uses this mapping:

```
LT -> ¯1
EQ -> 0
GT -> 1

min -> ⌊
max -> ⌈
compare -> (×-)
(<>) -> {⍺=0:⍵⋄⍺}

```

# Answer
> 1 votes
# Charcoal, 55 bytes

```
ＦＡ≡ιS⊞υ⌊Ｅ²⊟υB⊞υ⌈Ｅ²⊟υC⊞υ⁻›§υ±¹§υ±²‹⊟υ⊟υO⊞υ⊟ΦＥ²⊟υ∨κλ⊞υιＩυ

```

Try it online! Link is to verbose version of code. Takes input as a list in reversed Polish with reversed arguments, i.e. the entire Polish is simply reversed. Key: `-1` \- `LT`; `0` \- `EQ`; `1` \- `GT`; `S` \- `min`; `B` \- `max`; `C` \- `compare`, `O` \- `(<>)`. Explanation:

```
ＦＡ≡ι

```

Loop over the input list and switch over each element.

```
S⊞υ⌊Ｅ²⊟υ

```

Handle `S` by pushing the minimum of the top two values to the stack.

```
B⊞υ⌈Ｅ²⊟υ

```

Handle `B` by pushing the maximum of the top two values to the stack.

```
C⊞υ⁻›§υ±¹§υ±²‹⊟υ⊟υ

```

Handle `C` by comparing the top two values. (This is tricky when I don't have a comparison operator.)

```
O⊞υ⊟ΦＥ²⊟υ∨κλ

```

Handle `O` by pushing the first non-zero value of the top two values, if any. (I can't use `Or` itself because it's short-circuiting and would not remove the second value if the first was non-zero.)

```
⊞υι

```

Just push any other values to the stack.

```
Ｉυ

```

Output the final stack (which should hopefully be just one value at this point).

# Answer
> 1 votes
# Uiua 0.10.0, 7 bytes

```
quote^!

```

Try on Uiua Pad!

This is a macro that takes a string in reverse Polish notation and outputs the result. We use the mapping:

* `GT -> 1`
* `EQ -> 0`
* `LT -> ¯1` (or ``1`)
* `min -> ↧` (or `min`)
* `max -> ↥` (or `max`)
* `comp -> ¯±-` (or ``sig-`)
* `(<>) -> ±++.` (or `sig++.`)

Similar to the Vyxal solution, this evaluates the given string as code. We have to use a macro rather than the 6-byte function `quote∘` since quote's function cannot take input by default. As you can see, the entire code and test cases can be written entirely in ASCII, which is rare for Uiua.

# Answer
> 1 votes
# Scala 3, 157 bytes

A port of @Mukundan314's Python 2 answer in Scala.

---

Golfed version. Attempt This Online!

```
type Q=(Int,Int)=>Int
def f(s:Seq[_]):(Seq[_],Int)=s match{case(q:Q)::t=>val(r1,r2)=f(t);val r3=f(r1);(r3._1,q(r2,r3._2));case v::t=>(t,v.asInstanceOf[Int])}

```

Ungolfed version. Attempt This Online!

```
object Main {
  // Function type for operations
  type Op = (Int, Int) => Int

  def main(args: Array[String]): Unit = {
    // Define the recursive function `f`
    def f(s: List[Any]): (List[Any], Int) = s match {
      case (op: Op) :: tail =>
        val (rest1, result1) = f(tail)
        val (rest2, result2) = f(rest1)
        (rest2, op(result1, result2))
      case value :: tail => (tail, value.asInstanceOf[Int])
    }

    // Define the mappings (functions) for clarity
    val m: Op = (x, y) => Math.min(x, y)
    val M: Op = (x, y) => Math.max(x, y)
    val c: Op = (x, y) => x.compareTo(y)
    val s: Op = (x, y) => x | y

    // Examples of using the function `f`
    println(f(List(c, 0, 1))._2)
    println(f(List(s, -1, 1))._2)
    println(f(List(M, 0, m, 1, -1))._2)
    println(f(List(M, m, 1, -1, 0))._2)
    println(f(List(s, 0, s, 0, 0))._2)
    println(f(List(s, 0, s, 0, 1))._2)
    println(f(List(s, -1, c, -1, -1))._2)
    println(f(List(c, s, 1, 0, -1))._2)
    println(f(List(c, s, 0, 1, m, M, 0, 1, -1))._2)
  }
}

```

---
Tags: code-golf, logic-gates, combinatory-logic
---


# Question
Title: Transform characters of your choice into "Hello, world!"
Write a program or function that takes a character as input and outputs a character. Also, choose a list of 13 distinct ASCII printable characters (32-126). When a character from this list is passed into the program or function, it should output the character at the corresponding position in `Hello, world!`. This way, running your code on each element of the list in turn would produce `Hello, world!`.

**Example:**

If your chosen list is `Troublemaking`, you should produce a program or function that maps:

```
T -> H
r -> e
o -> l
u -> l
b -> o
l -> ,
e ->
m -> w
a -> o
k -> r
i -> l
n -> d
g -> !

```

**Rules:**

* Your score is length of the program/function.
* You can't store any data between program/function runs.
* Include list of the characters you chose into the answer.

# Answer
# Perl 5, 8 bytes

−1 byte by Sisyphus.

```
y;yav;ol

```

Input: `Heavy, world!` Try it online!
> 16 votes

# Answer
# Python 3, 18 bytes

A function that inputs and outputs an ASCII code.

```
lambda c:c-954%c%3

```

Try it online!

The chosen 13-byte string is: `Helmo,"yprnd!`, and was found using brute force.

**Alternative Solutions**

```
lambda c:c^656%c%7    # 18b ('Mahim/!sntjd"')
lambda c:c^308268%c   # 19b ('Z{@HU 2I}B`Y5')
lambda c:c|2242944%c  # 20b ('HeLdi, AoblD!')
lambda c:c^c*2%54%21  # 20b ('Ngchb"+|i{lt,')
lambda c:c-c*c%60%11  # 20b ('Mjmpr-#|tvqe$')

```
> 13 votes

# Answer
# JavaScript (Node.js), 14 bytes

```
c=>'lol'[c]||c

```

Try it online!

Input text is:

```
Hel0o, w1r2d!

```

lol
> 9 votes

# Answer
# Python, 31 bytes

```
lambda c:c.translate('ll !o'*8)
```

Attempt This Online!

Input characters to use are `Hel#o, w"r$d!`
> 8 votes

# Answer
# JavaScript (ES6), 16 bytes

Expects and returns an ASCII code.

Produces `Hello, world!` when given `(a-IK*s]d5P/+`.

```
c=>28+c*c%389%96

```

Try it online!

---

# JavaScript (ES6), 19 bytes

This version was built such that the output character is guaranteed to be in the range 32-126 as well. The OP has since clarified that this is not required.

Expects and returns an ASCII code.

Produces `Hello, world!` when given `,X=CI:YWx.~7-`.

```
c=>32+c*c*71%193%91

```

Try it online!

### Full mapping

```
   | 0 1 2 3 4 5 6 7 8 9 A B C D E F
---+--------------------------------
20 | M < S B Y = I - 9 m y G H ! r @
30 | 6 T J h S f Q d D L , 4 d l 6 3
40 | c U z l + x 7 y - o # Z i : > u
50 | n ? 8 Y R s a w e   ^ i L W / /
60 | b b / / W L i ^   e w a s R Y 8
70 | ? n u > : i Z # o - y 7 x + l

```
> 7 votes

# Answer
# Jelly, 6 bytes

```
“½ṬṚ»y

```

Try it online!

Takes `Heacn, wmrld!`. Searched with this script.

```
     y    Transliterate the input by
“½ṬṚ»     "monoclinal".

```

Unless I brute-forced something wrong, a 2-byte compressed string does not seem to be possible.
> 7 votes

# Answer
# 05AB1E, ~~7~~ 5 bytes

```
∞'Ÿ™‡

```

Uses `H2345, world!` as 13 characters.

Try it online or verify each ASCII character separately.

**Explanation:**

```
∞      # Push an infinite positive list: [1,2,3,...]
 'Ÿ™  '# Push dictionary string "hello"
    ‡  # Transliterate the characters of the (implicit) input-string
       # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `'Ÿ™` is `"hello"`.
> 7 votes

# Answer
# x86 32-bit machine code, 7 bytes

```
A8 28 75 02 0C 6C C3

```

Try it online!

Using the `regparm(1)` calling convention, this takes an ASCII code in AL and returns one in AL.

Chooses `He@DG, world!`.

In assembly:

```
f:  test al, 0b00101000 # Set flags based on bits 3 and 5 of the character.
    jnz e               # If they are not both 0 (true for all of "Hello, world!"),
                        #  jump to the end, to leave the character unchanged.
    or al, 0b01101100   # Otherwise, set bits 2, 3, 5, and 6 to 1.
                        # (These are the bits that are 1 in both 'l' and 'o'.)
e:  ret                 # Return.

```
> 7 votes

# Answer
# Retina 0.8.2, 7 bytes

```
T`d`o-l

```

Try it online! Explanation: Inspired by @loopywalt's Python answer, works by translating `0` to `o` and both `3` and `4` to `l`, so given the 13 distinct characters `Hel3o, w0r4d!` as input the output is `Hello, world!` as desired. (The full transliteration actually maps `0123456789` to `onmlllllll`.)
> 5 votes

# Answer
# Nibbles, ~~6.5~~ 6 bytes (12 nibbles)

```
=`r\$d:"lo"

```

`"Hel1o, w2r4d!"` becomes `"Hello, world!"`.

```
   \$d          # keep only digit characters
 `r             # and get the value
                # (so non-digits become zero)
=               # and use this to index into
        "lo"    # the string "lo"
       :        # with the input character appended
                # (wrapping around for index >3)

```
> 5 votes

# Answer
# Vyxal, 6 bytes

```
kakH¡Ŀ

```

Try it Online! Takes `a`, `b`, ... `m`

```
     Ŀ # Transliterate
ka     # Lowercase alphabet
  kH¡  # To corresponding chars of "Hello, world!"

```
> 4 votes

# Answer
# C (clang), 23 bytes

```
f(c){return 656%c%7^c;}

```

Try it online!

Takes `Mahim/!sntjd"`. Brute forced solution found using this program.

# C++ (clang), 22 bytes

```
[](int&c){c^=656%c%7;}

```

Port of the above.

Try it online!
> 4 votes

# Answer
# Bash, 9 bytes

```
tr 012 ol

```

Takes `Hel1o, w0r2d!`

Try it online!
> 4 votes

# Answer
# Python, 32 bytes

```
lambda c:"Helo, wrd!"[ord(c)%10]
```

Attempt This Online!

Takes in characters `[F,G,H,R,I,J,K,L,S,M,\,N,O]`.

## Python, 35 bytes

```
lambda c:"Hello, world!"[ord(c)-97]
```

Attempt This Online!

Takes in `[a,b,c,d,e,f,g,h,i,j,k,l,m]`.
> 3 votes

# Answer
# JavaScript (V8), 12 bytes

```
c=>c-954%c%3

```

Try it online!

Using the string `Helmo,"yprnd!`, ported from dingledooper's answer

Expects input as a charcode and outputs as the charcode
> 3 votes

# Answer
# K (ngn/k), ~~26~~ 21 bytes

```
"Hello world!"`i$-97+

```

*Down 5 bytes thanks to Razetime*

A port of Adam's Python answer. Takes in `[a..l]`.

Try it online!
> 1 votes

# Answer
# Charcoal, 9 bytes

```
⭆Ｓ§⁺ιloΣι

```

Try it online! Link is to verbose version of code. Takes as input the 13 distinct characters `He142, world!`. Explanation: Works by mapping `147` to `l` and `258` to `o`.

```
 Ｓ          Input string
⭆           Map over characters and join
    ι       Current character
   ⁺        Concatenated with
     lo     Literal string `lo`
  §         Cyclically indexed by
        ι   Current character
       Σ    Digit value (0 if not a digit)

```
> 1 votes

# Answer
## Knight, 13 bytes

```
O-=cP%%954c 3

```

Port of @dingledooper's answer.

## Knight, 16 bytes

```
O+28%%^P2 389 96

```

Port of @Arnauld's answer.
> 0 votes

# Answer
# Headascii, 45 bytes

```
-----[]]]]]--[]]]][U-]()R-:-()R--:--()R-:R;P!

```

Takes a character and prints it, except for `m`, `n`, and `p`, which map to `l`, `l`, and `o` specifcially. Full chosen string therefore is `Helmo, wprnd!`

Try It In Headass!, which is the same except that it takes character codes as input and returns character codes. Or, run it in Headascii here by pasting this in:

```
erun("-----[]]]]]--[]]]][U-]()R-:-()R--:--()R-:R;P!","x")

```

and replacing `x` with the character input of your choice.

Or verify the whole thing at once like this lol:

```
> hellowarp="-----[]]]]]--[]]]][U-]()R-:-()R--:--()R-:R;P!"
'-----[]]]]]--[]]]][U-]()R-:-()R--:--()R-:R;P!'
> verify=x=>erun(hellowarp,x)
[Function: verify]
> "Helmo, wprnd!".split("").forEach(verify)
H
e
l
l
o
,

w
o
r
l
d
!

```

### Explanation

```
-----[]]]]]--[]]]][U-]()R-:-()R--:--()R-:R;P!  full program
-----[]]]]]--[]]]][                            r2 = -108
                   U                           i = input (charcode)
                   U-]()                       if(i - r2 - 1 == 0){       // m
                        R-:               ;P!    print i - 1              // m - 1 == l
                          :-()                 }else if(i - r2 - 2 == 0){ // n
                              R--:        ;P!    print i - 2              // n - 2 == l
                                 :--()         }else if(i - r2 - 4 == 0){ // p
                                      R-: ;P!    print i - 1              // p - 1 == o
                                        :      }else{
                                         R;P!    print i
                                               }

```
> 0 votes

# Answer
# Pip, 9 bytes

```
"0ol"@a|a

```

Uses `Hel2o, w4r5d!`: Attempt This Online!

### Explanation

```
"0ol"@a|a
     @a   ; Use the input character as an index (if non-digit, treat as 0)
"0ol"     ; into this string (indexing is cyclical: 0->"0", 2->"l", 4->"o", 5->"l")
       |  ; If the result is falsey (i.e. "0"),
        a ; return the input character instead

```
> 0 votes

---
Tags: code-golf, hello-world, open-ended-function
---


# Question
Title: Print the last, middle and first character of your code
The challenge is simple: Print the last, middle, and first character of your program's source code, in that order.

The middle character is defined as follows, assuming a source length of `n` characters, and 1-indexing:

* If `n` is even, print the `n/2`-th and `n/2 + 1`-th character. (`abcdef == cd`)
* If `n` is odd, print `(n-1)/2 + 1`-th character. (`abcde == c`)

### Rules

* Given no input, print the last, middle, and first character in your source code, in the form `[last][middle][first]`. This will be 3-4 characters long.
* Output must not contain any trailing whitespace. However, if whitespace is a first, middle, or last character, it must be printed as such.
* Source code must be `n >= 3` characters long.
* Code must consist of `>= 3` unique characters.
* Standard loopholes are forbidden.
* This is , so shortest solution *in characters* wins.

### Samples

```
# Form: [code] --> [output]
xyz --> zyx
abcd --> dbca
1 --> # not allowed: too short
abcde --> eca
aaabb --> # not allowed: not enough unique characters
System.out.print("S;pr"); --> ;prS
this is a test --> ts t
123[newline]45 --> 53[newline]1

```

Challenge Proposal

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=188005;
var OVERRIDE_USER=78850;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```

```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```

# Answer
# JavaScript, ~~9~~ 7 bytes

```
N=>a=-N

```

Outputs: `NaN`

Try it online!
> 202 votes

# Answer
# Grass, 17 bytes

```
wWWwwwVVwWWwWWWww

```

Try it online!

-2 bytes thanks to jimmy23013.

Outputs `www`. Grass ignores all characters apart from `w`, `W` and `v`. The two `V`s are thus ignored; they are there to ensure the middle character is a `w` – I have no idea how to output `v` or `W` in Grass… I could have used another character instead of `V`, but `V` preserves the aesthetic of the code.
> 23 votes

# Answer
# brainfuck, 17 bytes

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

```

Try it online!

With unprintables this can be reduced to 7 bytes: `␀..␀_.␀`
> 21 votes

# Answer
# Shakespeare Programming Language, 119 bytes

```
 ,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]
Ajax:  You big big big big big cat.Speak thy.Speak thy.Speak thy.

```

Try it online!

Prints three spaces. Without printing spaces:

# Shakespeare Programming Language, 227 bytes

```
,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:You is the sum of a big big big big big big cat a big pig.
You is the sum of you a large huge large big pig.
Speak thy.Speak thy.You is the sum of you a big pig.Speak thy.

```

Try it online!

Like my newline-free INTERCAL answer, this is constructed to make the last character of the program the same as the middle character (although in this case it is not also the first), by un-golfing the second half of the code until they match. (I'm not sure if I could have constructed 46 in fewer bytes or not, or if I could have golfed other parts of the first half more.)
> 18 votes

# Answer
# Python 2, ~~13~~ 11 bytes

```

print' t'

```

To make the whitespace clear:

```
$ xxd solution.py
0000000: 0a70 7269 6e74 2720 7427 20           .print' t'
$ python2 solution.py | xxd
0000000: 2074 0a                                t.

```

Try it online!

<sub>-2 bytes, thanks to wastl !</sub>
> 15 votes

# Answer
# 05AB1E, ~~7~~ 5 bytes

```

„ RR
```

Outputs `R \n`.

-2 bytes by taking inspiration from *@Neil*'s Batch answer, so make sure to upvote him as well!

Try it online.

**5 bytes alternative by *@Grimy*:**

```

12,1
```

Outputs `12\n`.

Try it online.

**Initial 7 bytes answer:**

```
'?„«'«?

```

Outputs `?«'`.

Try it online.

**Explanation:**

```
          # No-op newline
„ R       # Push 2-char string " R"
   R      # Reverse this string to "R "
          # (output the result implicitly with trailing newline)

          # No-op newline
12,       # Print 12 with trailing newline
   1      # Push a 1 (no implicit printing, since we already did an explicit print)

'?       '# Push 1-char string "?"
  „«'    '# Push 2-char string "«'"
     «    # Concatenate them both together
      ?   # Output without trailing newline

```
> 13 votes

# Answer
# RProgN 2, 3 bytes

```
1
0

```

Try it online!

I think this is valid?
> 10 votes

# Answer
# Jelly, 5 bytes

```
001 0

```

Try it online!

The output has two distinct characters, but the code also has a third one.

Trivial 4-byte version:

```
1231

```
> 9 votes

# Answer
# PHP, 9 bytes

```
<?=";;<";

```

Try it online!
> 8 votes

# Answer
# Excel, 9 bytes

```
=("))=" )

```

So many Parentheses.

Note: The returned middle character can actually be any character since it's the middle of the code.
> 8 votes

# Answer
# DOS/Windows Batch Language, 9 bytes

```
@echo @o@

```
> 7 votes

# Answer
## Batch, 9 characters

```

@echo hh
```

The middle and last character are both `h`, and then the `echo` prints a newline by default, which is the first character of the script.
> 6 votes

# Answer
# Ruby, 6 bytes

```

p " "

```

Try it online!

This outputs `" "` plus a newline. The code ends with a `"`, the middle two characters are  and `"`, and it starts with a newline.
> 6 votes

# Answer
# PowerShell, 3 bytes

```
00000000: 0a0d 31                                  ..1

```

Works only in Microsoft Windows.

The output is unfortunately 8 bytes in UTF-16. But the question says output the characters, and not the bytes. Arguably UTF-16 is just one of the supported ways to represent the characters in PowerShell. They are not interpreted differently from an ASCII file.
> 6 votes

# Answer
## Bash (15 11 characters)

```
echo -n e-e

```

which prints out

```
e-e

```
* -4 chars by not using `|rev`
> 6 votes

# Answer
# Underload, ~~9 bytes~~ 7 bytes

Thanks to Khuldraeseth na'Barya for the improved solution!

```
W(SSW)S

```

As for as I can tell, this is now unimprovable since:

* The first character has to be a no-op character, since every other instruction raises an error due to the stack being empty, with the exception being an opening bracket. However, it can't be that since there is no way to output an opening bracket on it's own in Underload.
* You need to use at least 5 characters to add the 3 output characters to the stack.
* You need to use S to output it.

Try it online!
> 6 votes

# Answer
# Shakespeare Programming Language, ~~163~~ 153 bytes

-10 bytes thanks to Jo King.

```
B,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:You is
the sum ofa Big Big Big BIG BIG cat a
CAT.Speak thy.You is twice you.Speak thy!SPEAK THY!

```

Try it online!

My first SPL answer! Outputs `!BB`.

There is another SPL answer by Unrelated String; in that answer, they output only spaces in 119 bytes, or output non-space characters in 227 bytes. This one comes in between, and also outputs non-space characters.

Two tricks are used here:

1. An SPL sentence can end with `!` rather than `.`, and `!` is easier to get since its ASCII codepoint is 33 (=\\$2^5+1\\$), whereas the codepoint of `.` is 46.
2. Doubling 33 gives 66, the codepoint of `B`, hence the play title is `B` and I need the second "big" to be "Big", which works since SPL is case-insensitive.

Since I needed that capital `B` and an exclamation mark at the end, I decided to have Ajax shout louder and louder through the scene.
> 6 votes

# Answer
It feels cheaty, but

# Mornington Crescent, 1005 bytes

```
Take Northern Line to Euston

Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Gunnersbury
Take District Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Upminster
Take District Line to Gunnersbury
Take District Line to Victoria
Take Victoria Line to Tottenham Hale
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take District Line to Gunnersbury
Take District Line to Acton Town
Take District Line to Acton Town
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Leicester Square
Take Northern Line to Leicester Square
Take Northern Line to Mornington Crescent

```

There are nine deliberately placed newlines after the first instruction to make the middle character the `o` of `Take District Line to Upminster`. The code prints out the first three characters of `Tottenham Hale` reversed to yield `toT`. Of course, this challenge was made easier by the fact that Mornington Crescent programs always start with the `T` of `Take` and end with the `t` of `Mornington Crescent`, barring any extra newlines.
Try it online!
> 6 votes

# Answer
# Ruby, ~~11~~ 9 bytes

```
print:ptp

```

Try it online!
> 5 votes

# Answer
# ArnoldC, 61 bytes

```
IT'S SHOWTIME
TALK TO THE HAND "D I"
YOU HAVE BEEN TERMINATED

```

Try it online!

Trivial answer in ArnoldC. The 31st byte is the space just before the string literal.
> 5 votes

# Answer
# Chef, 447 bytes

```
Last Middle First Milkshake.

This recipe prints its last, middle and first character.
You could also use it to make a milkshake.

Ingredients.
76 ml milk
32 ml chocolate syrup
46 teaspoons vanilla ice cream

Method.
Liquefy vanilla ice cream.
Put the milk into 1st mixing bowl.
Put the chocolate syrup into 1st mixing bowl.
Put the vanilla ice cream into 1st mixing bowl.
Pour contents of the 1st mixing bowl into the 1st baking dish.

Serves 1.

```

Try it online!

# A serious submission, ~~196~~ 177 bytes

## thanks to A\__

```
R.

Ingredients.
82 l a
103 l b
46 l c

Method.
Put a into mixing bowl.
Put b into mixing bowl.
Put c into mixing bowl.
Pour contents of mixing bowl into baking dish.

Serves 1.

```

Try it online!
> 5 votes

# Answer
# TI-Basic, 3 bytes

```
i+1

```

`i` represents the imaginary number.
> 5 votes

# Answer
# Knight, 7 bytes

```

O"OO"O

```

Try it online!

Prints `OO<newline>`.

Whitespace is ignored, `O` is monadic output function which prints the string `"OO"` without quotes and a trailing newline, and the last `O` is ignored because the parsing ends at `O"OO"`.

# Knight, 7 bytes

```

O-1 2-

```

Try it online!

Prints `-1<newline>`.
> 5 votes

# Answer
# CJam, 7 bytes

```
'@'' _@

```

Try it online!
> 4 votes

# Answer
# C (gcc), 21 bytes

```

main(){puts("}u");;}

```

Try it online!
> 4 votes

# Answer
# Whitespace, ~~31~~ 29 bytes

```
[S aS S T   S S S S S N
_Push_32][S N
S _Duplicate_32][S N
S _Duplicate_32][T  N
S S _Print_as_character][T  N
S S _Print_as_character][T  N
S S _Print_as_character]

```

-2 bytes thanks to *@RobinRyder*.

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs, and new-lines only).

Contains a no-op `a` (can be any non-whitespace character) to make the length odd. It is added before the first halve of the program so the middle character is a space as well, since the middle character would have become a newline if it was at the second halve of the program. All non-whitespace characters are ignored in Whitespace programs.
> 4 votes

# Answer
# Befunge-93, 7 bytes

```
.",  @0

```

Try it online!

## Explanation

Output is `0 .`

```
.       pop value (0) from stack, output as number with a trailing space
 "      toggle string mode, wraps around and pushes every char to the stack
  ,     pop value (".") from stack, output as character
        spaces are no-ops
     @  end the program
      0 trailing 0 to match the output

```
> 4 votes

# Answer
# APL (Dyalog Unicode), ~~5~~ 4 bytes

Full programs.

Boring solution from J.Sallé:

```
1231

```

Prints that number. A much more interesting solution:

```
010E1

```

Try it online!

APL ignores leading zeros, so this is simply scaled format for 10×10¹=100.
> 4 votes

# Answer
# Brain-Flak, 11 bytes

```
(((())))

```

Try it online!

## Explanation

We need to put 3 things on the stack. The fastest way to do that is to put 3 1s (or zeros) on the stack. Now since `` (code point 1) does nothing in Brain-Flak we can add these to the program at the first middle and last places. Now this feels a bit cheaty so here are two more answers that are less cheaty in my opinion.

# Prints braces, 31 bytes

```
( (((((()()()()()){}){}){}))())

```

Try it online!

This answer prints braces so that the characters printed are actually relevant to the code, it does have one padding character to make the length odd so we only have to print 1 middle character.

# Contains only braces, 32 bytes

```
(((()((((()(()()){}){}){}){}))))

```

Try it online!

This is a braces only program both the source and (consequently) the output are made up entirely of braces (character Brain-Flak actually cares about).
> 4 votes

# Answer
# Python 3, 19 bytes 13 bytes

```

print( ')(')

```

The print function appends a newline by default so the code starts with a newline. The last character of the code is a ")" so that's printed first. To make the number of characters uneven, a space in inserted before the argument of the print function. Please excuse the salaciousness of the code.

Outputs: `)(\n`

Try it online.
> 4 votes

# Answer
# 33, 9 bytes

```
a"a\\a"pa

```

The a's do nothing here, they're essentially NOPs in this code to make it shorter. My original thought was `"p\\\""p`, but that's 8 bytes, so it needs to print another `\`, making it 10 bytes `"p\\\\\""p`

This is a language I did create, but I made it legitimately, so I hope it's within the rules.
> 4 votes

# Answer
# Husk, 5 bytes

```
"¨ ¨"

```

Try it online! In Husk, `¨` is the escape character for `"`.
> 4 votes

# Answer
# Haskell, 17 bytes

```
main=putStr"\"Sm"

```

Try it online!
> 3 votes

# Answer
# Java 8, 11 bytes (as lambda function)

```
v->'"'+"'v"

```

Outputs `"'v`.

Try it online.

# Java 8, 67 bytes (as full program)

```
interface M{static void main(String[]ar){System.out.print("}ni");}}

```

Outputs `}ni`.

Note the `ar` instead of `a` as argument. Otherwise the middle part had to be `in`, but printing that would make the size odd again, which would cause a paradox-loop..

Try it online.
> 3 votes

# Answer
# MathGolf, ~~5~~ 4 bytes

```
1231

```

-1 byte by using the trivial solution presented by *@ErikTheOutgolfer* in his Jelly answer, which works for any language with implicit output without trailing newline.

Try it online.

**Original 5 bytes answer:**

```
ùù xx

```

Outputs `x ù`.

Try it online.

**Explanation:**

```
ùù x   # Push 3-char string "ù x"
    x  # Reverse it to "x ù"
       # (output the entire string joined together implicitly without trailing newline)

```
> 3 votes

# Answer
# , 11 bytes

```
cat("))c" )

```

Try it online!

Outputs `))c`. Space added to make the number of characters odd: otherwise we would need to output 4 characters, and that would make the code longer anyway.
> 3 votes

# Answer
**HQ9+ 4 characters**

`+AQ+`

Explanation:

```
+ ; increment accumulator
A ; nop
Q ; print itself
+ ; increment accumulator

```
> 3 votes

# Answer
# Forth (gforth), 9 bytes

Prints an escape-supporting string.

```
.\"   ."

```

**Try it online**

---

### Also 9 bytes:

Prints three spaces.

```
 ."    "

```

**Try it online**

---

### 9 bytes with Stack Underflow:

```
 ." .. ".

```

**Try it online**

---

The 2nd and 3rd solutions also work if you replace first quotations with `(` and last quotes with `)`. Essentially, plenty of ways to do it in 9 bytes, but probably not any shorter.

Documentation
> 3 votes

# Answer
# INTERCAL, 65 bytes

```
PLEASE,1<-#3DO,1SUB#1<-#246DON'TPARSE!!
DO READ OUT ,1
DO GIVE UP

```

Try it online!

Padding the second half of the program to make the output `PPP` seems to be shorter than printing multiple distinct characters.

```
PLEASE ,1 <- #3         Declare that the length of the uint16 array ,1 is 3.
DO ,1 SUB #1 <- #246    Make the first element of ,1 246. (The other elements are 0.)
DON'T PARSE!!           This statement is ignored and nonsense.
DO READ OUT ,1          Print ,1 using C-INTERCAL's "Turing Tape" I/O.
DO GIVE UP              End the program.

```

This one *almost* works for 35 bytes, but it prints a space before the first newline:

```

PLEASE       READ OUT#500DOGIVEUP

```
> 3 votes

# Answer
# MATLAB, 13~~15~~ bytes

```
disp(  ') d')

```

Outputs `) d`

Previous version (15 bytes, less strict output):

```
'''';1;''''''''

```

Outputs `'''`
> 3 votes

# Answer
# AsciiDots \- 9 bytes

```
.---$'.$.

```

Output: `.$.`

The code starts with a `.`, ends with a `.`, and the middle character is a `$`. The single quote in the middle sets the dot print mode to simply read characters straight into the output stream.

It is possible that this could be made smaller, but I'm starting to doubt that it can. In order to print three characters, the single quote must be used, as the double quote would require an end to the string in order to output. However, this means that the single quote has to a) be followed by three characters and b) cannot be the center character. In order to crunch this down to seven bytes, I was considering trying to reuse the dot's start as one of the printed characters (sort of like AsciiDot's quine program). However, I found that the shortest sequence available for printing was `($'` which would have had to print four characters in the space of three, or three characters in the space of four. I also tried some hacky alternative methods like trying to print the dot's value (which is 0) as one of the characters. While there may be some system that works, I've found these to be rather complex and large. Thus, I think that the above is the smallest solution. (I will update if I find something smaller)
> 3 votes

# Answer
# GolfScript, ~~7~~ 5 bytes

```

".".

```

Try it online!

## Explanation

```
     # A newline, just to hide the effect of the automatic trailing newline
"."  # The . character: the last and middle character
   . # Copy the character twice

# Implicitly output the whole stack without a delimiter.

# This returns ".." (the . character duplicated) and a trailing newline.

```
> 3 votes

# Answer
# Itr, 5 characters (6 bytes)

`×'×3×`

online interpeter

## Explanation

```
×'×3×
×     ; call × on the first two arguments (0 by default) and ignore the result
 '×   ; the character ×
   3× ; repeated 3 times

```
> 3 votes

# Answer
## AppleScript, 4

```
1021

```

Outputs the last char (`1`), the middle chars (`02`), and the first char (`1`).

Any four-digit number with the same first and last digits and different middle digits works.
> 2 votes

# Answer
# JavaScript (Babel Node), 11 bytes

```
_=>(')\)_')

```

Try it online!
> 2 votes

# Answer
# Kotlin, ~~39~~ 25 bytes

```
fun main(){print("}rf")
}

```

Try it online!

Edit: -14 bytes thanks to @daniero
> 2 votes

# Answer
# PowerShell, ~~8~~ 7 bytes

```

' D'

```

Try it online!

Notice the two spaces after the last quote. Forgot that using implicit output puts a newline afterwards. Fixing that saved a byte though.

## Alternative 7 byte solution with 3 unique chars by mazzy

```

"`"`""

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), 9 bytes

```
⎕←'''''⎕'

```

Try it online!

Both the last and middle characters are `'`, while the first is .
> 2 votes

# Answer
# Stax, 5 bytes

```

.PPP

```

Run and debug it at staxlang.xyz!

The leading linefeed does nothing. `.PP` pushes the string `PP`, and the final `P` prints it with a trailing newline. The last character is `P`, the middle character is the first `P`, and the first character is a linefeed.

The implicit print's trailing linefeed invalidates the 4-byte solutions `1231` and `.S.S` (adapted from Weijun Zhou's quine).
> 2 votes

# Answer
# Python 3 ~~12~~ 13 bytes

```
input(r')ri')

```
> 2 votes

# Answer
# Forth (gforth), 13 bytes

```
: f ." ; :" ;

```

Try it online!

### Code Explanation

```
: f         \ start a new word definition
  ." ; :" ; \ print "; :"
;           \ end the word definition

```
> 2 votes

# Answer
# Gaia, 5 bytes

```

⌋ ”⌋

```

Try it online!

The  is just there as a no-op.

```
            % helper function
⌋ ”⌋         % main function: push "⌋ " and convert to lowercase
            % then implicitly print with trailing newline

```
> 2 votes

# Answer
# Charcoal, 7 bytes

```
←´←´´´X

```

Try it online! The final `X` could be any byte in the Charcoal code page except `0xFF` and the two already in use. Works by printing the desired characters leftwards. Alternative approach, also 7 bytes:

```
←”y←←”y

```

Try it online! The final `y` could be any ASCII character but I picked `y` because of the symmetry. Works by printing two s leftwards so that the final character gets printed at the start of the output.
> 2 votes

# Answer
# PowerShell, 7 bytes

Another trivial solution. The first and the last lines contains `LF`.

```

"`nn"

```

Try it online!

---

# PowerShell, 9 bytes

non-trivial, no byte sequence hacks. The first line contains `LF` only. The second line starts with a space.

```

 echo hh

```

Try it online!
> 2 votes

# Answer
# dc, 9 characters

```
[PP]P91aP

```

Sample run:

```
bash-5.0$ dc -e '[PP]P91aP'
PP[

```

Try it online!
> 2 votes

# Answer
# Japt, 5 bytes

Inspired by my JavaScript solution.

```
N'a*N

```

Try it
> 2 votes

# Answer
# Wolfram Language (Mathematica), 9 bytes

```

Pri**n**t@nn

```

Try it online!
> 2 votes

# Answer
# PHP, 11 bytes

```
<?=';\\<';;

```

Try it online!
> 2 votes

# Answer
## Keg, ~~7~~ 5 bytes

```
1\':'

```

This prints `''1`, which are the respective characters.

No Try It Online available for Keg.

Here is an uninteresting 4-byte answer:

```
1231

```
> 2 votes

# Answer
# C++ (clang) (lambda expression), 17 bytes

```
[]{return "}n[";}

```

Try it online!

---

# C++ (clang) (full program), ~~47~~ 43 bytes

```

#import<ios>
int main() {std::puts("}n");}

```

Try it online!

Unfortunately had to leave an extra space in both of the solutions, to make them have an odd number of characters.
> 2 votes

# Answer
# Zsh, 9 bytes

```

<<<\<\<

```

Try it online!

Hexdump, with first/middle/last bytes highlighted:

```
00000000: 0a0a 3c3c 3c5c 3c5c 3c                   ..<<<\<\<
          F^        M^        L^                   ^   ^   ^

```

Output is `<<[newline]`.
> 2 votes

# Answer
# Bitwise Cyclic Tag But Way Worse, 26 bytes

```
ÿ1111111122ÿ2000000002ÿ

```

Outputs `ÿ ÿ ÿ`. 26 bytes since ÿ is considered 2 bytes in UTF-8.

Try it Online!
> 2 votes

# Answer
# Cubix, 9 bytes

```

oN/
@oo

```

Try it online!

Reasonably boring one. Since the newlines in the first, middle and last positions are ignored by the interpreter the code wraps onto the following cube. Spaces could be used as well. eg `oS/ @oo`

```
  o
N / @ o
  o

```

Watch it run

* `N` Pushs 10 (newline) onto the stack.
* `/` redirects around the cube.
* `ooo` outputs the newline 3 times.
* `/@` redirects again and halts the program
> 2 votes

# Answer
# Haskell, 19 bytes

```

main=($LT)print--L

```

Try it online! Outputs `LT<newline>`.
> 2 votes

# Answer
# C#, 71 bytes

```
public class P{public static void Main(){System.Console.Write("pa}");}}

```

Try Online
I don't think I need to explain anything here
> 2 votes

# Answer
# Lost, 21 bytes

```
v<<<<<>>>>>
>%?"v>@"@

```

Outputs: `v>@`.

Try it online or verify that it's deterministic.

### Explanation:

**Explanation of the language in general:**

Lost is a 2D path-walking language. Most 2D path-walking languages start at the top-left position and travel towards the right by default. Lost is unique however, in that ***both the start position AND starting direction it travels in is completely random***. So making the program deterministic, meaning it will have the same output regardless of where it starts or travels, can be quite tricky.

A Lost program of 2 rows and 5 characters per row can have 40 possible program flows. It can start on any one of the 10 characters in the program, and it can start traveling up/north, down/south, left/west, or right/east.

In Lost you therefore want to lead everything to a starting position, so it'll follow the designed path you want it to. In addition, you'll usually have to clean the stack when it starts somewhere in the middle.

**Explanation of the program:**

All arrows, including the `>v` in the string, will lead the path towards the leading `>` on the second line. From there the program flow is as follows:

* `>`: travel in an east/right direction
* `%`: Put the safety 'off'. In a Lost program, an `@` will terminate the program, but only when the safety is 'off'. When the program starts, the safety is always 'on' by default, otherwise a program flow starting at the exit character `@` would immediately terminate without doing anything. The `%` will turn this safety 'off', so when we now encounter an `@` the program will terminate (if the safety is still 'on', the `@` will be a no-op instead).
* `?`: Clean the top value on the stack. In some program flows it's highly likely we have a partial string on the stack, so we use this to wipe the stack clean of that potential string.
* `"`: Start a string, which means it will push the integer code-points of the characters used (rather similar as the Whitespace program).
* `v>@`: Push the code-points for these characters, being `118 62 64` respectively
* `"`: We're done pushing code-points of this string
* `@`: Terminate the program if the safety is 'off' (which it is at this point). After which all the values on the stack will be output implicitly. Using the `-A` program argument flag these code-points will be output as characters instead.

Two things to note:

The top part could also have been `v<<<<<<<<` instead. Lost will wrap around to the other side when moving in a direction. So using `v<<<<>>>>` could be a slightly shorter path, and since it's the same byte-count anyway, why not use it. :)
Also, the first line contains an additional `<` and `>`. One of them is to avoid having the newline character as the middle of the program, which is rather difficult to output and would have only increased the byte-count. The second is to make the program length odd again, so we'd only have to output a single middle character instead of two.
> 2 votes

# Answer
# 6502, 17/21 bytes

**6502: 17 bytes if running in zero page**

For initial testing I used Py65, a 6502-based microcomputer simulator written in Python. Starting Py65 with the command-line parameter `-o ff` moves the character output port to zero page address $FF, shaving three bytes from the code.

The program must be loaded and run at $0000, to guarantee outputing the correct three characters (in order) from the program with values `00` `B5` `A5`.

Here are the program bytes and their respective disassembly view in Py65:

```
.mem 0000:0010
0000:  a5  10  85  ff  a9  11  4a  aa  b5  00  85  ff  a5  00  85  ff  00

.d 0000:0010
$0000  a5 10     LDA $10
$0002  85 ff     STA $ff
$0004  a9 11     LDA #$11
$0006  4a        LSR A
$0007  aa        TAX
$0008  b5 00     LDA $00,X
$000a  85 ff     STA $ff
$000c  a5 00     LDA $00
$000e  85 ff     STA $ff
$0010  00        BRK

```

**6502: 21 bytes if running outside zero page**

Four additional bytes are required to allow the program to run outside of zero page. Three of the those bytes are the change in the LDA (load accumulator) instructions from zero page to absolute addressing. The fourth is the addition of a NOP (no operation) instruction, to maintain an odd number of bytes in the program.

This version of the program must be loaded and run at $0300, to guarantee outputing the correct three characters (in order) from the program with values `00` `00` `AD`.

Here are the program bytes (character values) and their respective disassembly view:

```
.mem 0300:0314
0300:  ad  14  03  85  ff  a9  15  4a  aa  bd  00  03  85  ff  ad  00  03  85
0312:  ff  ea  00

.d 0300:0314
$0300  ad 14 03  LDA $0314
$0303  85 ff     STA $ff
$0305  a9 15     LDA #$15
$0307  4a        LSR A
$0308  aa        TAX
$0309  bd 00 03  LDA $0300,X
$030c  85 ff     STA $ff
$030e  ad 00 03  LDA $0300
$0311  85 ff     STA $ff
$0313  ea        NOP
$0314  00        BRK

```

**6502: 21 bytes if running on an Apple II**

We've come this far, so let's plop this baby on an Apple II. I don't normally tote around my Apple //c anymore, so I used a2ix on my Android phone.

Instead of sending characters to an addressed port, they will go to COUT (character output), a routine in system ROM.

$0300 is the usual spot for small assembly routines, so that's where I'll enter and list it. Running it yields a flashing space (`60`), inverse N (`0E`), and a normal " (`A2`). On the Apple II, ASCII characters are remapped across the 256-character range to achieve different character effects in text mode.

```
*300: A2 14 20 0E 03 A9 15 4A AA 20 0E 03 A2 00 BD 00 03 20 ED FD 60

*300L

0300-   A2 14       LDX   #$14
0302-   20 0E 03    JSR   $030E
0305-   A9 15       LDA   #$15
0307-   4A          LSR
0308-   AA          TAX
0309-   20 0E 03    JSR   $030E
030C-   A2 00       LDX   #$00
030E-   BD 00 03    LDA   $0300,X
0311-   20 ED FD    JSR   $FDED
0314-   60          RTS

```

Relocating this to a free area of zero page (good luck!) would not yield any byte savings. While the absolute indexed LDA (load accumulator) at $030E could be switched to its zero page indexed counterpart to save one byte, an NOP (no operation) would have to be added to avoid additional code to support print two middle characters.
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
×'×3×

```

Try it online!

```
×   push a string of nothing, repeated nothing times (in other words, push an empty string)
'×  push "×"
3×  push "×", repeated 3 times
    implicitly print top of stack

```
> 2 votes

# Answer
# AWK, 17 bytes

```
BEGIN{print"}iB"}

```

Try it online!
> 2 votes

# Answer
# naz, ~~28~~ 24 bytes

```
0a9a3a9m3a2o0a0a0a0a0m2o

```

**Explanation**

```
0a9a3a9m3a2o # Output "o" twice
0a0a0a0a     # Padding bytes
0m2o         # Output "0" twice

```

Original 28-byte solution: `0a9a3a9m3a1o0a0a0a9s5s1o0m2o`
> 2 votes

# Answer
# Brainetry, 181 bytes

This program starts and ends with an upper case `L` and also has it in the middle of its source code. This golfed version is based off of the program that comes after it.

To try this online, follow this repl.it link, paste my source code in the `btry/replit.btry` file and hit the green "Run" button.

```
L b
a b c d
a b c d e f g h
a b c d
a b c
a b c d e f g h
a b c d e
a b c
a b c d e f g h L
a b
a b
a b c d
a b c d
a b c d e f g h i
a b c
a b c d e f g
a b c d e f g
a b c d e f L

```

The verbose version also starts and ends with an uppercase `L` and has one of those in the exact middle of its source code.

```
Lo and
behold: this program has
a self referential property! This code prints its
first, middle and last
chars! How nice!
Of course I cheated a little and made
this program in such a
way that all
3 of those chars are the upper case L,
which I
also had
to properly place in
the middle of this
text to make sure they appeared in those positions.
A bit of
luck and a bit of mathematics allowed
me to accomplish this feat. Let me
check it... Woops, missed by one... LOL

```
> 2 votes

# Answer
# Turing Machine Code, 29 bytes

```
0 * 2 r 1
1 * 1 r 2
2 * 0 * 2

```

Try it online!

Prints '210'.
> 2 votes

# Answer
# Jelly, 4 bytes

```
5235

```

Try it online!

pretty simple, no explination needed
> 2 votes

# Answer
# Malbolge, 67 bytes

Outputs `n D`. Eventually I thought a space is really necessary.

```
D'`_$"\\[||98V6Bu@tOq<.'98*ZjE&fe {Ab~,v*)]xZvonsl2ponmfN+cba`ed]#n

```

Try it online!
> 2 votes

# Answer
# GNU dc, 5 bytes

```
0p
n0

```

Try it online!

Pushes 0 to the stack, prints 0 with a new line, prints 0 without a new line and again pushes 0 to the stack.

`n` is a GNU implementation. Might not work with other versions.
> 2 votes

# Answer
# Lexurgy, 15 bytes

This was surprisingly difficult. Outputs `a>=a`.

```
abc:
*=>a\>\=a

```
> 2 votes

# Answer
# Pyramid Scheme, 115 bytes

```
   ^     ^
  / \   / \
 /out\ /out\
^-----^-----
-^   ^-
 -^ ^-
  -^-
  / \
 /chr\
^-----
-^
 -^
 / \
/32 \
-----

```

Try it online!

The middle character is the space after the ^ on the fifth line. Prints three spaces.
> 2 votes

# Answer
# Zsh, 9 bytes

```
print ptp
```

Attempt This Online!
> 2 votes

# Answer
# Pip, 7 bytes

```

R"R "

```

Attempt This Online! (Note the trailing space)

#### Explanation

```
\nR"R "   ; Full program
\n        ; No-op
   "R "   ; The string "R "
  R       ; Reversed
          ; No-op
          ; Implicit output
          ; (with newline)

```
> 2 votes

# Answer
# Elm 0.19, 11 bytes

```
f()="\"\\f"

```

Prints `"\f`. See it working here.
> 1 votes

# Answer
# Runic Enchantments, ~~9~~ 7 bytes

```
'@'':r@

```

Try it online!

-2 bytes by just using char literals. Outputs `@''`
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 19 bytes

```

	OUTPUT = 'D='
END

```

Try it online!

Prints `D=<newline>`, using SNOBOL's trailing newline in `OUTPUT`.

`D=`
> 1 votes

# Answer
# Lenguage, ~~292~~ 2340 bytes

*Thanks to Jimmy23013 for pointing out I need another 2048 bytes*

2340 bytes of any character with the first, middle two and last characters being a null byte.

Prints 4 null characters.

Try it online in brainfuck
> 1 votes

# Answer
# Haskell, 17 bytes

```
main=putStr"\"Sm"

```

Try it online!
> 1 votes

# Answer
# Lua, ~~31~~ 13 bytes

```
print (')(p')

```

Prints ***)(p***

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 7 bytes

```

01$*$$

```

Try it online! Retina 0.8.2 outputs a trailing newline by default, so the code starts with that. Conveniently, this also matches the default empty input, allowing the replace stage to get to work. It then suffices to come up with a string of even length \> 2 that outputs the other 2 characters.
> 1 votes

# Answer
# Retina, 7 bytes

```
((K`(`(

```

Try it online! Retina 1 does not output a trailing newline by default, but fortunately it has the `K` command which allows us to specify a constant string output. The grouping construct `(` is used to increase the number of distinct characters to meet the minimum requirement.
> 1 votes

# Answer
# Dodos, 22 bytes

```

	dot
	dot
0         0

```

Try it online!
> 1 votes

# Answer
# Japt, 7 bytes

```
''ixi''

```

Try it

```
''ixi''
''          :Literal "'"
  i         :Prepend
   x        :  Literal "x" (any lowercase letter would work. Except i, of course)
    i       :  Prepend
     ''     :    Literal "'"

```

## Alternatives

```
"\"ww"w

```

Try it

```

Riii'R
```

Try it

```
"Q\""+Q

```

Try it
> 1 votes

# Answer
# Brachylog, 7 bytes

```
"w\\""w

```

Try it online!

*Thanks to Shaggy for correcting this to comply with the challenge specification.*

Boring string literal, except thanks to the weird way Brachylog string literals work, the escaped backslash also still escapes the quote afterwards, so it's not actually that boring.
> 1 votes

# Answer
# Gema, 13 characters

```
\A=l\\\\@fail

```

Try it online!
> 1 votes

# Answer
# Perl 5, 11 bytes

```
say "\"\\s"

```

Try it online!
> 1 votes

# Answer
# HTML, 4 bytes

```
^db^
```

```
^<X>_<X>^
```

I'm not sure if this is cheating... Really.

First one also worked as PHP ~~or Text~~.
> 1 votes

# Answer
# MarioLANG, 53 bytes

```
+>(-[!)
+"===#+
++
++
++
++
++
 +
)!)  <...
=#==="==+

```

Try it online!

Output: `+++`. The 27th character is one of the `+` characters in the second column of the code.
> 1 votes

# Answer
# cQuents, 8 bytes

```
1#11,2&1

```

Try it online!

Outputs `11,1`.

# Explanation

```
1             Prepend 1 to the output
 #11,2        Default input is `11, 2`
      &       Output as many terms as the last input, comma seperated
       1      Each term equals 1

```

So first 1 is prepended, then the input becomes `11,2`. Then, we output 2 terms comma separated, which is `1,1`, so the final output is `11,1`.
> 1 votes

# Answer
# Bash, ~~9~~ ~~11~~ 9 bytes

## First attempt:

```
echo e\ o

```

Output

```
e o

```

---

## Second attempt:

```
echo -n e-e

```

Output:

```
e-e

```

---

## Third attempt

```

echo  oo

```

Note the leading newline and the double space

Output:

```
oo

```
> 1 votes

# Answer
# BitCycle, 5 bytes

```

11!1

```

Try it online!

Outputs `11` with a trailing newline. Only the first pair of `1`s is actually printed.
> 1 votes

# Answer
# LOLCODE, 27 bytes

```
HAI 1
VISIBLE "E H"
KTHXBYE

```

Try it online!

Trivial answer in LOLCODE. The 14th character is the space just before the string literal.
> 1 votes

# Answer
# Perl 5, 11 bytes

```

 say '; ';

```

Try it online!

Note the initial newline and the trailing space. Outputs

```
;

```
> 1 votes

# Answer
# SmileBASIC, 7 bytes

```
?":b?":

```

Output: `:b?`

(Probably works in most BASIC dialects) The middle character can be anything except `"`, LF, and CR.
> 1 votes

# Answer
# F#, 13 bytes (characters)

So many esoteric languages that seem to be made specifically for code golfing… let's try a terse but 'normal' language like F#, where the following line (without a trailing newline) has 13 characters (13 bytes if the source file is saved as ANSI text):

```
printf"\"\"p"

```

Output:

```
""p

```
> 1 votes

# Answer
# Boolfuck, ~~29~~ 21 bytes

```
;;;;;;;;;;;;;;;;;+

```

Outputs 3 null characters

Thanks to Jo King for the improved solution!

Try it online!

## BitChanger, 23 bytes

```
<<<<<<<<<<}<<<}<}<}<

```

Very similar to the Boolfuck one: uses the fact the null characters require no bit changing to output with tape-based bit output

## How it works:

```
           Used as it is simple to output
<<<<<<<<<< Moves over to one left of the I/O bit
}           Sets the I/O bit to one, for output
<<<         Moves over to the bit that performs I/O
}<}<}       Sets it to one 3 times, to output 3 null characters
<          I used < to waste one byte so it could be an odd number of bytes

```

Try it Online!
> 1 votes

# Answer
# Pyth, 5 bytes

```

10 1

```

Prints `10` followed by a newline. Try it online!

Newlines normally print the next result followed by a newline, but at the start of a program it is essentially a no-op. `10` is the literal value, which is printed followed by a newline. The space before the `1` suppresses the usual implicit printing, so the final `1` is ignored.
> 1 votes

# Answer
# Octave, 15 bytes

```
fprintf(')(f' )

```

Try it online!

As far as I know, using `fprintf` is the only method of out that doesn't come with extraneous output.
> 1 votes

# Answer
# Python 2, ~~12 bytes~~ 11 bytes

```
Placeholder to make the leading newline visible

print"\"t"

```
> 1 votes

# Answer
# Rust (closure), 9 bytes

```
|| ";;|";

```

Try it online!

---

# Rust (full program), 25 bytes

```
fn main(){print!("}}if")}

```

Try it online!
> 1 votes

# Answer
# Pip, 15 bytes

```
O"}"xxL1{O"1O"}

```

Needs more golfing

Try it online!

# Pip, 9 bytes

```

O"nn"x
n

```

shorter version with newline

Try it online!

# Pip, 8 bytes

```
1x000Oh1

```

another one

Try it online!
> 1 votes

# Answer
# Ohm v2, 5 bytes

```
…Lo…L

```

Try it online!
> 1 votes

# Answer
# ink, 5 bytes

```

/a//

```

Prints `/a` and a newline

Try it online!
> 1 votes

# Answer
# DOS COM x86 binary

```
% xxd test.com
00000000: 31c9 4b88 2f80 ffef 75f8 8007 30b4 028a  1.K./...u...0...
00000010: 17cd 2180 3f00 7503 e905 00fe 0fe9 f3ff  ..!.?.u.........
00000020: b402 8a17 cd21 8007 20b4 028a 17cd 2190  .....!.. .....!.
00000030: cd20 4b53 20                             . KS

```
> 1 votes

# Answer
# x86-64 (Mac OS), 35 bytes

```
b8 04 00 00 02 bf 01 00 00 00 48 be 20 00 00 00
00 00 00 00 ba 03 00 00 00 0f 05 48 31 c0 c3 00
b8 00 b8

```

can be disassembled to:

```
[bits 64]

section .text
  global _main

_main:
  mov rax, 0x2000004
  mov rdi, 1
  mov rsi, x
  mov rdx, 3
  syscall
  xor rax, rax
  ret

section .data
  x: db 184, 0, 184

```

and compiled with:

```
$ nasm -fmacho64 FILE.asm
$ ld -fSystem FILE.asm

```

then run

```
$ ./a.out
<0xb8><0x00><0xb8>

```
> 1 votes

# Answer
# Python 3, 13 bytes

```
print(')\'p')

```

Try it online!
> 1 votes

# Answer
# Python 3, 13 bytes

This should suffice. Although it has a new line at the end of the output. There is a space in between print and '(' to make the total count of characters odd.

```
print (')(p')

```

Try it online!
> 1 votes

# Answer
## , 5 bytes

```

'+:+

```

## Explanation

<pre><code>     % Newline (no-op)
'+   % The addition operator
  :+ % Multiply the character twice
     % Print with a newline
```
</code></pre>
> 1 votes

# Answer
# , 11 characters

```
57125574032

```

Try it online!

Prints `255`.

## Explanation:

The program pushes **`5|7255|4632`** onto the frame (which starts with `||`). Then, the last section of the frame (**`4632`**) is executed.

**`4`** swaps the last two sections, and adds another bar between them. The frame is now **`||5|4632||7255`**.

**`6`** *pacifies* the last section of the frame by converting the active commands **`7255`** (shown in **bold**) to their passive equivalents `1255`, and removing the bar before it. The frame now looks like **`||5|4632|`**`1255`.

**`3`** outputs the last section of the frame (`1255`) and discards the last two sections. The initial `1` means "print the rest unchanged", so `255` is printed. Then, the last two sections are discarded, leaving **`||5`** on the frame.

**`2`** duplicates the last section of the frame, leaving **`||5|5`**. There are no more characters left on the command list, so the last section of the frame (**`5`**) is executed.

**`5`** moves the last section of the frame (which is another **`5`**) to the start of the command list to be executed immediately, and then discards it. This leaves **`||5`** on the frame.

This happens again, leaving **`5`** on the command list and `|` on the frame.

The last **`5`** moves the last section of the frame (i.e. nothing) to the command list, leaving an empty command list and an empty frame. This causes the program to exit successfully.

### Notes:

* The `57` at the beginning and the `2` at the end are included because without them, one of the first, middle, or last characters would have been a `7`, and printing `7` is hard.
* The program can fit into 4 *bytes*, but the question asks to minimize *characters*.
> 1 votes

# Answer
# Width, 7 bytes

```
GAPSfeW

```

Try it online!

Outputs through STDERR.

I used a `G` to start the string. The ID of `G` is `39`, which turns into `eW`. The ID of `W` is `55`, which turns into `AP`. Then I just used `Ai` which is `50`, and checked how close it was to `A`, saw it became `R`, then used `Sf`, which is `51`, and becomes `S`.
> 1 votes

# Answer
# Python 3, 13 bytes

`print(")\"p")`

Try It Online!

Having `"` as the middle char is lucky, because then I can balance the parity of the code because it requires an escape sequence.

There's a few more Python 3 13-byters, so I imagine this is the shortest possible solution. I don't there's a shorter solution with `exit()`, which prints to STDERR.
> 1 votes

# Answer
# Grok, 11 bytes

```
iq i`  wwwq        # Prints "q i"

```
> 1 votes

# Answer
# Scratch, 23 bytes

```
when gf clicked
say[wcw

```
> 1 votes

# Answer
# Racket, 15 bytes

```
(display "(y)")

```

Try it online!
> 1 votes

# Answer
# BRASCA, 5 bytes

```
9C9$9

```

Try it!

## Explanation

```
9            - Push 9
 C           - Set implicit output to number mode
  9          - Push 9
   $         - Swap the two nines
    9        - Push 9
<implicit>   - Output stack

```
> 1 votes

# Answer
# Vyxal `D`, 5 bytes

```

 ‛‛‛

```

Try it Online!

Note the trailing space and newline.

Simply pushes `‛‛`, and prints with trailing newline.
> 1 votes

# Answer
# Python 3, 13 bytes

```
print( ') p')

```

The last character is ')', the middle is number 7, a space and the first is the letter 'p'.
> 1 votes

# Answer
# Julia 1.0, 13 bytes

most python answers work with julia too, but here are a couple very julian 13-byters

```
"s" |>show;""
"t|\""|>print

```

Try it online!
> 1 votes

# Answer
# Vyxal, 7 bytes

No flags used.

```
9 99J₴9

```

## Explanation

```
9        - Push 9
  99     - Push 99
    J₴   - Concatenate and print
      9  - Pushes another 9, but it never gets used.

```

Try it Online!
> 1 votes

# Answer
# Pari/GP, 13 bytes

```
print1(")("p)

```

Try it online!
> 1 votes

# Answer
# Microscript II, 10 bytes

Welcome to Backslash Hell

`"\"\\\\\""`

I suspect that a shorter version is possible.
> 1 votes

# Answer
# Flobnar, 7 bytes

```
0..0#@0

```

Try it online!

The character that is easiest to print is the digit `0`. 5 bytes is impossible because it mandates three zero digits and a `@` at one of the two positions (2nd or 4th), which makes the program print 0 only once. For 7 bytes, we skip a 0 with `#` and print zero twice using `.` (explicit decimal output); the third copy of 0 is produced as the value that `@` evalautes to.
> 1 votes

# Answer
# Thunno, \\$7\log\_{256}(96)\approx\\$ 5.76 bytes

```

Z" rr

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
\n\nZ" rr
\n\n       # no-ops
    Z" r   # 2-char string: " r"
        r  # reverse to get "r "
           # implicit output with newline

```
> 1 votes

# Answer
# Go, 25 bytes

```
func()string{return"}nf"}

```

Attempt This Online!

Function which returns a string.

# Go, 35 bytes

```
import."fmt"
func f(){Print("} i")}

```

Attempt This Online!

Function which prints to STDOUT.

# Go, 51 bytes

```
package main
import."fmt"
func main(){Print(`}
p`)}

```

Attempt This Online!

Full program which prints to STDOUT.
> 1 votes

# Answer
## Python REPL, 5 bytes

`122-1`

yields 121.

This probably works with many other interactive environments as well, but this is the shortest I could think of.
> 1 votes

# Answer
# Desmoslang, 9 Bytes

```
1OOO1ETG1

```

Outputs 111
> 1 votes

# Answer
# Swift 5.9, 13 bytes

```

print (") ")

```

This is basically a Swift version of this Python answer by @TFeld. Prints the last character `")"`, the middle character `" "` (a space), and the first character `"\n"` (a newline, printed thanks to `print(_:separator:terminator:)`'s default `terminator` of `"\n"`).
> 1 votes

# Answer
# Pxem, Filename: 9 bytes + Content: 0 bytes = 9 bytes.

* Filename: `O.ooo.o.O`
* Content: empty
> 0 votes

# Answer
# abcn, 15 bytes

```
a120gxgxnba98gx

```

## Explanation :

```
a120                  --> sets stack at 120
gx                    --> convert to ASCII and print (120 ==> x) as you can see x is last char
gx                    --> convert stack 120 again to ASCII and print `x` mid char (7th) is x
                      --> as well (a120gxg make 7 and nba98gx make 7 so we print x)
b                     --> stack set to -1 (useless just made so we print x twice and
                      --> not have to add more bytes)
a98                   --> add to stack 98 (giving us 97)
gx                    --> convert to ASCII and print (97 == a) a is first char

```

prints `xxa` which is the right answer
> 0 votes

# Answer
# Java (JDK), 9 bytes

```
$->"  $"

```

Try it online!
> 0 votes

# Answer
# CLC-INTERCAL, 67 bytes.

Outputs `1#D`. It was difficult to adjest program length. Eventually I decided to do `\#9`; this caused no side effects.

```
DO;1<-#9\#9DO;1SUB#1<-#100DO;1SUB#2<-#374DO;1SUB#3<-#276DOREADOUT;1

```

Copy and paste to try it online!
> 0 votes

# Answer
# FerNANDo, 53 bytes

Outputs `aaa`, but is it accepted...?

```
a a a
z a a z z z z a
z a a z z z z a
z a a z z z z a

```

Try it online!
> 0 votes

# Answer
# Ly, 9 bytes

```
'o:oo"'"o

```

Try it online!

I had some more interesting versions (IMO anyway), but they were longer. :)

```
 'o         - push "o" on the stack
   :        - duplicate top of stack
    oo      - print both "o" chars
      "'"   - load a doublequote on the stack
         o  - print it

```

Prints output `oo"`
> 0 votes

# Answer
# DipDup, 7 bytes

```
a[aaa]a

```

Try it online!
> 0 votes

# Answer
# Python 3, 15 15 bytes

```
print("  p")

```

Try it online!

## Previous answer(Incorrect)

```
print("pp ")

```

The answer is no longer pp （◞‸◟）
> 0 votes

# Answer
## Pascal, 41 characters

NB: Despite appearing that way the source code has *no trailing newline*:

```
program p(output);begin write('.gp')end .

```
> 0 votes

# Answer
# Thunno 2, 5 bytes

```

` rr

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer. Prints `r \n`.

**Alternative 5 bytes:**

```

12£1

```

Attempt This Online!

Port of Kevin Cruijssen's alternative 05AB1E answer. Prints `12\n`.
> 0 votes

# Answer
## COBOL, 67 B

The OpenCOBOL implementation does not seem to process non-lines (i. e. a character sequence that is *not* concluded by a newline character). Therefore the COBOL source code contains *a* newline character. However, I did not achieve printing a *leading* newline character (there was *a space* I could not get rid of). So I extended the source code with some syntactically acceptable junk. The `01` is *not* followed by a newline character.

```
000000 PROGRAM-ID.P.PROCEDURE DIVISION.DISPLAY"1I0"NO ADVANCING.
01

```

Output: `1I0`
> 0 votes

---
Tags: code-golf, self-referential
---