title: Animate finding the middle

text:
# Question
Title: Animate finding the middle
Given a non-empty string, keep removing the first and last characters until you get to one or two characters.

For example, if the string was `abcde`, your program should print:

```
abcde
 bcd
  c

```

However, if it was `abcdef`, it should stop at two characters:

```
abcdef
 bcde
  cd

```

Trailing newlines and trailing spaces at the end of each line are optional. You can have as many as you want or none.

## Test cases

```
ABCDEFGHIJKLMNOPQRSTUVWXYZ -> ABCDEFGHIJKLMNOPQRSTUVWXYZ
                               BCDEFGHIJKLMNOPQRSTUVWXY
                                CDEFGHIJKLMNOPQRSTUVWX
                                 DEFGHIJKLMNOPQRSTUVW
                                  EFGHIJKLMNOPQRSTUV
                                   FGHIJKLMNOPQRSTU
                                    GHIJKLMNOPQRST
                                     HIJKLMNOPQRS
                                      IJKLMNOPQR
                                       JKLMNOPQ
                                        KLMNOP
                                         LMNO
                                          MN

ABCDEFGHIJKLMNOPQRSTUVWXYZ! -> ABCDEFGHIJKLMNOPQRSTUVWXYZ!
                                BCDEFGHIJKLMNOPQRSTUVWXYZ
                                 CDEFGHIJKLMNOPQRSTUVWXY
                                  DEFGHIJKLMNOPQRSTUVWX
                                   EFGHIJKLMNOPQRSTUVW
                                    FGHIJKLMNOPQRSTUV
                                     GHIJKLMNOPQRSTU
                                      HIJKLMNOPQRST
                                       IJKLMNOPQRS
                                        JKLMNOPQR
                                         KLMNOPQ
                                          LMNOP
                                           MNO
                                            N

A -> A

AB -> AB

```

Remember this is , so the code with the smallest number of bytes wins.

# Answer
# , 10 bytes

```
ò^llYpr $x

```

Try it online!

Explanation:

```
ò^ll         " While there are at least two non-whitespace characters on the current line
    Y        " Yank this line
     p       " Paste it below
      r      " Replace the first character with a space
        $    " Move to the end of the line
         x   " Delete a character

```
> 12 votes

# Answer
# ES6 (Javascript), ~~47~~, ~~48~~, 43 bytes

EDIT: Replaced ternary operator with &&, prefixed padding string with the newline. Thanks @Neil for an excellent advice !

EDIT: included the function name for the recursive invocation, stripped one byte off by using a literal newline

**Golfed**

```
R=(s,p=`
 `)=>s&&s+p+R(s.slice(1,-1),p+' ')

```

**Test**

```
R=(s,p=`
 `)=>s&&s+p+R(s.slice(1,-1),p+' ')

console.log(R("ABCDEFGHIJKLMNOPQRSTUVWXYZ"))

ABCDEFGHIJKLMNOPQRSTUVWXYZ
 BCDEFGHIJKLMNOPQRSTUVWXY
  CDEFGHIJKLMNOPQRSTUVWX
   DEFGHIJKLMNOPQRSTUVW
    EFGHIJKLMNOPQRSTUV
     FGHIJKLMNOPQRSTU
      GHIJKLMNOPQRST
       HIJKLMNOPQRS
        IJKLMNOPQR
         JKLMNOPQ
          KLMNOP
           LMNO
            MN

console.log(R("ABCDEFGHIJKLMNOPQRSTUVWXYZ!"))

ABCDEFGHIJKLMNOPQRSTUVWXYZ!
 BCDEFGHIJKLMNOPQRSTUVWXYZ
  CDEFGHIJKLMNOPQRSTUVWXY
   DEFGHIJKLMNOPQRSTUVWX
    EFGHIJKLMNOPQRSTUVW
     FGHIJKLMNOPQRSTUV
      GHIJKLMNOPQRSTU
       HIJKLMNOPQRST
        IJKLMNOPQRS
         JKLMNOPQR
          KLMNOPQ
           LMNOP
            MNO
             N

```
> 9 votes

# Answer
## Python, 45 bytes

```
f=lambda s,p='\n ':s and s+p+f(s[1:-1],p+' ')

```

Recursively outputs the string, plus a newline, plus the leading spaces for the next line, plus the recursive result for the shortened string with an extra space in the prefix.

If a leading newline was allowed, we could save a byte:

```
f=lambda s,p='\n':s and p+s+f(s[1:-1],p+' ')

```

Compare with a program (49 bytes in Python 2):

```
s=input();p=''
while s:print p+s;s=s[1:-1];p+=' '

```
> 8 votes

# Answer
# Brainfuck, 67 bytes

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

```

This should work on all brainfuck flavors.

Try it online!

### Ungolfed code:

```
# Print and read input_string into memory
>>,[.>,]<
while input_string is not empty [
    # Print newline
    >+++++ +++++.<
    # Remove last character
    [-]
    # GOTO start of input_string
    <[<]>
    # Remove first character
    [-]
    # Add space to space_buffer
    +++++ +++[-<++++>]
    # GOTO start of space_buffer
    <[<]>
    # Print space_buffer
    [.>]
    # Print input_string
    >[.>]
<]

```

There should still be some bytes to chop off here; I've only recently began using brainfuck, so my pointer movement is probably very inefficient.
> 6 votes

# Answer
# , 39 19 16 bytes

```
[:|:]#"0~#\.<.#\

```

Try it online!

This was a nice example of how a different perspective can allow J to express a problem more naturally. Originally, I was seeing the problem "horizontally", as described in the OP -- a sequence with successive edges being removed:

But you can also view it vertically, as a kind of upside down histogram:

From this perspective, we are just repeating each letter some number of times, an operation J's copy primitive `#` can accomplish in 1 character.

Consider `abcde`:

* `#\.<.#\` Determine the number of times to repeat each character, ie, produce the mask `1 2 3 2 1`:

```
#\  => 1 2 3 4 5
#\. => 5 4 3 2 1
----------------
<.  => 1 2 3 2 1  NB. elementwise min

```
* `]#"0~` Use that mask to duplicate the input:

```
a
bb
ccc
dd
e

```
* `[:|:` Transpose:

```
abcde
 bcd
  c

```
> 6 votes

# Answer
# Python 2, 50 bytes

```
def f(i,j=0):
 print' '*j+i
 if i:f(i[1:-1],j+1)

```

Simple recursive function that keeps shortening the string until it disappears.

Call as f('string')

Output

```
string
 trin
  ri

```
> 5 votes

# Answer
## Perl, 31 bytes

30 bytes of code + `-p` flag.

```
s/( *)\S(.+).$/$&
 $1$2/&&redo

```

To run it :

```
perl -pE 's/( *)\S(.+).$/$&
 $1$2/&&redo' <<< "abcdef"

```

**Explanations** : The `\S` and `.$` correspond to the first and last character, `(.+)` the middle and `( *)` to the trailing spaces that are added every time we remove one character from the beginning. So the regex removes one character from the beginning, one from the end, and add one leading space each time.
> 5 votes

# Answer
# GNU sed 24 Bytes

Includes +2 for `-rn`

```
:
p
s/[^ ](.+)./ \1/
t

```

Prints, replaces the first non-space character with a space, and deletes the last character until nothing changes.
> 4 votes

# Answer
# MATL, 9 bytes

```
tg!*YRPRc

```

This produces trailing spaces and newlines.

Try it online!

### Explanation

```
t      % Input string implicitly. Duplicate
g!     % Convert to logical and transpose: gives a column vector of ones
*      % Multiply with broadcast. This gives a square matrix with the string's
       % ASCII codes on each row
YR     % Lower triangular part: make elements above the diagonal 0
P      % Flip vertically
R      % Upper triangular part: make elements below the diagonal 0
c      % Convert to char. Implicitly display, with char 0 shown as space

```
> 3 votes

# Answer
## Batch, 92 bytes

```
@set/ps=
@set t=
:g
@echo %t%%s%
@set t= %t%
@set s=%s:~1,-1%
@if not "%s%"=="" goto g

```

Takes input on STDIN.
> 3 votes

# Answer
# C, 73 bytes

```
f(char*s){char*b=s,*e=s+strlen(s)-1;while(e-b>-1)puts(s),*b++=32,*e--=0;}

```

Ungolfed:

```
f(char*s) {
  char *b=s,
       *e=s+strlen(s)-1;
  while (e-b>-1)
    puts(s),
    *b++=32,
    *e--=0;
}

```

Usage:

```
main(){
  char a[] = "abcde";
  f(a);
}

```
> 3 votes

# Answer
# 05AB1E, 8 bytes

Code:

```
ÐvNú,¦¨D

```

Explanation:

```
Ð          # Triplicate the input
 v         # Length times do...
  Nú,      # Prepend N spaces and print with a newline
     ¦¨    # Remove the first and the last character
       D   # Duplicate that string

```

Uses the **CP-1252** encoding. Try it online!
> 3 votes

# Answer
## Pyke, 10 bytes

```
VQlRc
l7tO

```

Try it here!
> 3 votes

# Answer
# Haskell, ~~47~~ 43 bytes

```
f s@(a:b:c)=s:map(' ':)(f.init$b:c)
f s=[s]

```

Try it on Ideone. Output is a list of strings which was allowed in the comments of the challenge. To print, run with `(putStr.unlines.f)` instead of just `f`.

Edit: Saved 4 bytes after noticing that trailing whitespace is allowed.

```
Prelude> (putStr.unlines.f)"codegolf"
codegolf
 odegol
  dego
   eg
               --(trailing whitespace)

```
> 3 votes

# Answer
# Perl 6, 42 bytes

```
for get,{S/\w(.*)./ $0/}.../\s..?$/ {.put}

```

## Expanded:

```
for

  # generate the sequence
  get,       # get a line from the input

  {          # bare block lambda with implicit parameter ｢$_｣
             # used to produce the rest of the sequence

    S/       # replace
      \w     # a word character ( to be removed )
      (      # set ｢$0｣
        .*   # any number of any characters
      )
      .      # any character ( to be removed )
    / $0/    # append a space

  }

  ...        # repeat that until

  /          # match
    \s       # whitespace
    .        # any character
    .?       # optional any character
    $        # end of string
  /

{
  .put       # print $_ with trailing newline
}

```
> 3 votes

# Answer
# Vyxal `C`, 4 bytes

```
‡ḢṪ↔

```

Try it Online!

i have turned to the dark side

i am now a flag abuser

thanks to lyxal for helping me get to the 4-byte sol (from 8 bytes)

## Explanation

```
   ↔  While results have not reached a fixed point
‡     2-byte function
 Ḣ    a[1:]
  Ṫ   a[:-1]

C     Center the list and join on newlines

```

The below less cheese program does the same thing. `øĊ` is the same as the `C` flag.

# Vyxal `j`, 6 bytes

```
‡ḢṪ↔øĊ

```

Try it Online!

Since outputting a list was allowed, using the `j` flag to join on newlines is reasonable. You can also append  to use no flags at all.
> 3 votes

# Answer
# Jelly, 9 bytes

```
J’⁶ẋoUµ⁺Y

```

Try it online!

If the input is of length \\$2n\\$, this outputs with \\$n\\$ lines of trailing newlines and spaces

## How it works

```
J’⁶ẋoUµ⁺Y - Main link. Takes a string A on the left
      µ⁺  - Do the following twice:
J         -   Yield [1, 2, 3, ..., 2n]
 ’        -   Decrement; [0, 1, 2, ..., 2n-1]
  ⁶ẋ      -   Repeat a space that many times; [[], [' '], [' ', ' '], ...]
     U    -   Reverse A
    o     -   Logical OR
        Y - Join by newlines

```

The logical OR command `o` has the following behaviour:

```
[[], [5], [6, 7], [8, 9, 10]] o [1, 2, 3, 4] = [[1, 2, 3, 4], [5, 2, 3, 4], [6, 7, 3, 4], [8, 9, 10, 4]]

```

so only the leftmost characters are replaced by spaces. We do this twice, reversing each time, to get both the left and right side
> 2 votes

# Answer
# Canvas, 9 bytes

```
［Ｌ［ｊｋ｝］∔＼

```

Try it here!
> 2 votes

# Answer
## Retina, 17 bytes

```
;{G:`
\S(.+).
 $1

```

Try it online!
> 1 votes

# Answer
# C++14, 117 bytes

```
auto f(auto s){decltype(s)r;auto b=s.begin();auto e=s.rbegin();while(e.base()-b>0)r+=s+"\n",*b++=32,*e++=0;return r;}

```

Assumes input `s` is a `std::string` and returns the animated text.

Ungolfed:

```
auto f(auto s){
  decltype(s)r;
  auto b=s.begin();
  auto e=s.rbegin();
  while(e.base()-b>0){
    r+=s+"\n";
    *b++=32;
    *e++=0;
  }
  return r;
}

```

Usage:

```
main(){
  std::string a{"abcdef"};
  std::cout << f(a);
  std::string b{"abcde"};
  std::cout << f(b);
}

```
> 1 votes

# Answer
## Vim - 14 keystrokes

```
qqYp^r $x@qq@q

```

Explanation:

```
qq  -- record a macro named 'q'
Y   -- Copy current line
p   -- Paste it
^r  -- Replace the first non-space character on the new line with a space
$x  -- Delete the last character on the line
@q  -- Recursively call the 'q' macro
q   -- Stop recording the 'q' macro
@q  -- Run the 'q' macro

```

Vim automatically kills the macro once we're out of characters
> 1 votes

# Answer
**Snap! - 16 blocks**

Output is self-centering. The 'wait' is for humans.
> 1 votes

# Answer
# PHP, 91 bytes

```
<?for(;$i<.5*$l=strlen($s=$_GET[s]);$i++)echo str_pad(substr($s,$i,$l-$i*2),$l," ",2)."\n";

```

Usage: save in a file and call from the browser:

```
http://localhost/codegolf/string-middle.php?s=ABCDEFGHIJKLMNOPQRSTUVWXYZ

Raw output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
 BCDEFGHIJKLMNOPQRSTUVWXY
  CDEFGHIJKLMNOPQRSTUVWX
   DEFGHIJKLMNOPQRSTUVW
    EFGHIJKLMNOPQRSTUV
     FGHIJKLMNOPQRSTU
      GHIJKLMNOPQRST
       HIJKLMNOPQRS
        IJKLMNOPQR
         JKLMNOPQ
          KLMNOP
           LMNO
            MN

http://localhost/codegolf/string-middle.php?s=1ABCDEFGHIJKLMNOPQRSTUVWXYZ

Raw output:
1ABCDEFGHIJKLMNOPQRSTUVWXYZ
 ABCDEFGHIJKLMNOPQRSTUVWXY
  BCDEFGHIJKLMNOPQRSTUVWX
   CDEFGHIJKLMNOPQRSTUVW
    DEFGHIJKLMNOPQRSTUV
     EFGHIJKLMNOPQRSTU
      FGHIJKLMNOPQRST
       GHIJKLMNOPQRS
        HIJKLMNOPQR
         IJKLMNOPQ
          JKLMNOP
           KLMNO
            LMN
             M

```
> 1 votes

# Answer
**Mathematica, 71 bytes**

```
Table[#~StringTake~{i,-i},{i,Ceiling[StringLength@#/2]}]~Column~Center&

```
> 1 votes

# Answer
# Stax, 7 bytes

```
ö÷e╧╤ù◘

```

Run and debug it

## Explanation

```
|]miTiNt
|]m      map each suffix to:
   iT    remove iteration count elements from right
     iNt pad with iteration count number of spaces on left

```

# Stax, 117 bytes

```
c%{d
   xitiT|c
   {|,}20*|:xi{xitiTx%|CPFxP
   {|,}20*|:xi{xitiTx%|CPFxitiNtP
   {|,}20*|:xi{xitiTx%|CPFxitiTx%|CP
F

```

Run and debug it, animated

The more fun version. Since stax supports `requestAnimationFrame` from js, `|,` and `|:` can be used to animate each step.
> 1 votes

# Answer
# Pyth, 11 bytes

```
.e
:bUkd_._

```

Test suite

14 bytes to exit without error
> 1 votes

# Answer
# APL (Dyalog Unicode), ~~25~~ ~~16~~ 15 bytes

-9 bytes thanks to Jonah's comment!
-1 bytes thanks to Adám!

```
{⍉↑⍵/¨⍨⌊∘⌽⍨⍳⍴⍵}

```

Try it online!

This is the dfn taking the string as right input .

`⍳⍴⍵` the indices of the input string.
`⌊∘⌽⍨` element-wise minimum of the indices with the indices reversed. This is the number of times each character appears.
`⍵/¨⍨` repeat each character that many times.
arranges the repeated characters in a 2d matrix, padding shorter strings with spaces.
transposes the matrix.

Try it with step-by-step output!
> 1 votes

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


title: Write an interpreter for *

text:
# Question
Title: Write an interpreter for *
The task is simple. Write an interpreter for the language .

Here's a bigger link to the wiki.

There are only three valid * programs:

* `*` Prints "Hello World"
* `*` Prints a random number between 0 and 2,147,483,647
* `*+*` Runs forever.

The third case must be an infinite loop according to the specifications in this question

## Input:

* The input can be taken via any acceptable input method by our standard I/O rules
* It will always be one of the above programs

## Output:

* The first case should print exactly `Hello World`, with or without a trailing line break.
* For the second case, if your language's integer maximum is smaller than 2,147,483,647, use your language's integer maximum
* The first and second cases can print to any acceptable output by our standard I/O rules.
* The third case should not give any output.

## Scoring:

As this is , the shortest answer, in bytes, wins.

# Answer
> 25 votes
## , 0 bytes

```

```

Since * has no way of reading input, the default rules allow specifying that the input must be given by concatenating it onto the program.

(... I think. There's an *"at least twice as many upvotes as downvotes"* condition that I don't have the rep to verify).

# Answer
> 10 votes
# , 69 bytes

```
switch(scan(,""),"*"="Hello, World!"," * "=sample(2^31,1)-1,repeat{})

```

Try it online!

`switch` tries to match the named arguments and if there's no match, selects the first unnamed one after the first, which in this case is the infinite loop `repeat{}`.

# Answer
> 8 votes
# Jelly,  ~~21~~  20 bytes

```
ḊOSØ%HX’¤“½,⁾ẇṭ»¹Ḃ¿?

```

A monadic Link accepting a list of characters.

**Try it online!**

`vL’...` also works (see below).

### How?

```
ḊOSØ%HX’¤“½,⁾ẇṭ»¹Ḃ¿? - Link: list of characters   e.g.: "*"        or  " * "    or  "*+*"
Ḋ                    - dequeue                          ""             "* "         "+*"
 O                   - to ordinals                      []             [42,32]      [43,42]
  S                  - sum                              0              74           85
                   ? - if...
                  ¿  - ...if-condition: while...
                 Ḃ   -    ...while-condition: modulo 2  0              0            1
                ¹    -    ...while-true-do: identity                                85
                     -                                  0              74           (looping)
        ¤            - ...then: nilad followed by link(s) as a nilad:
   Ø%                -    literal 2^32                                 2^32
     H               -    half                                         2^31
      X              -    random integer in [1,n]                      RND[1,2^31]
       ’             -    decrement                                    RND[0,2^31)
         “½,⁾ẇṭ»     - ...else: dictionary words        "Hello World"

```

---

Alternative

```
vL’... - Link: list of characters                 e.g.: "*"        or  " * "    or  "*+*"
 L     - length                                         1              3            3
v      - evaluate (left) as Jelly code with input (right)
       -                                                1^1            3^3          (3^3+3)^3
       -                                                1              27           27000
  ’    - decrement                                      0              26           26999
   ... - continue as above                              "Hello World"  RND[0,2^31)  (looping)

```

# Answer
> 6 votes
# C (gcc), 66 63 bytes

Thanks to attinat for the -3 bytes.

I only have to check the second character: if the LSB is set, it's a `+` (thus the program is "`*+*`") and the program loops. After that, if it's a `NUL`, the program was "`*`" and we display `Hello World`; otherwise, it displays a random value ("`*`", the only other option left.)

```
f(char*s){for(s++;*s&1;);printf(*s?"%d":"Hello World",rand());}

```

Try it online!

# Answer
> 6 votes
# Keg, `-lp`, `-ir` ~~30~~ ~~26~~ ~~25~~ ~~24~~ ~~20~~ 19 bytes

```
!1=[_“H%c¡“| =[~.|{

```

*-1 byte using flags*

Try it online!

## Answer History

```
?!1=[_“H%c¡“| =[~.|{

```

Try it online!

Shortened `Hello World` to dictionary string

```
!1=[_Hello World| =[~.|{

```

Try it online!

I never ceased to be amazed at the power of Keg. Credits to user EdgyNerd for another byte saved.

## Prior Versions

```
_!0=[Hello World|\*=[~.|{

```

Try it online!

Credit to user A\__ for the extra byte saved.

## Old version

```
?!1=[_Hello World| =[__~|{

```

Essentially, takes the input program and:

* Checks to see if the input length is 1, printing "Hello World" if true
* Checks to see if the last character is a space, and prints a random number
* Otherwise runs an infinite loop

Then implicitly print the stack.

```
?                               #Get input from the user
 !1=                            #Compare the stack's length to 1
    [_Hello World           #Push "Hello, World!" to the stack
                     | =        #See if top item is a space
                        [__~|{  #If so, generate a random number, otherwise, infinite loop.

```

4 bytes saved due to the fact that hello world doesnt need punctuation.

Try it online! Old version

Try it online! New version

# Answer
> 5 votes
# Python 2, ~~103~~ ~~93~~ ~~89~~ 87 bytes

I combined my earlier answer with Chas Browns's answer and got something a few bytes shorter.

The random number will be between 0 and 2\**31-1 inclusive.

```
from random import*
i=input()
while'*'<i:1
print["Hello World",randrange(2**31)][i<'!']

```

**Try it online!**

### Previous versions:

103 bytes

```
from random import*
exec['print"Hello World"','while 1:1','print randint(0,2**31-1)'][cmp(input(),'*')]

```

93 bytes

```
from random import*
i=cmp(input(),'*')
while i>0:1
print["Hello World",randint(0,2**31-1)][i]

```

# Answer
> 5 votes
# Japt, 22/25 bytes

The first solution is for the original spec which had `*<space>` as the second programme and the other is for the updated spec which arbitrarily changed it to `<space>*</space>`, with thanks to EoI for the suggested "fix".

Both throw an overflow error upon entering the infinite loop of the third programme but, theoretically, with enough memory (which we may assume for the purposes of ), would run forever.

```
Å?¢?ß:2pHÉ ö:`HÁM Wld

```

Try programme 1
Try programme 2
Try programme 3

```
Å?UÎ>S?ß:2pHÉ ö:`HÁM Wld

```

Try programme 1
Try programme 2
Try programme 3

# Answer
> 3 votes
# JavaScript (ES7), 66 bytes

```
s=>s[1]?s<'!'?Math.random()*2**31|0:eval(`for(;;);`):'Hello World'

```

Try it online! (Hello World)

Try it online! (random number)

Try it online! (infinite loop)

# Answer
> 3 votes
# Python 2, ~~91~~ ~~89~~ 88 bytes

```
from random import*
def f(p):
 while'*'<p:p
 print['Hello World',getrandbits(31)][p<'!']

```

Try it online!

2 bytes thanks to Jonathan Allan; 1 byte thx to ShadowRanger.

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

```
OS¹Ḃ¿ịØ%HX’;““½,⁾ẇṭ»¤

```

Try it online!

A monadic link taking a single argument and returning `Hello World`, a random 31 bit integer or looping infinitely as per the spec.

All options: `*` `*` `*+*`

## Explanation

```
O                     | Convert to codepoints
 S                    | Sum
  ¹Ḃ¿                 | Loop the identity function while odd
     ị              ¤ | Index into the following as a nilad:
      Ø%              | - 2 ** 32
        H             | - Halved
         X            | - Random integer in the range 1..2**31
          ’           | - Decrease by 1
           ;          | - Concatenated to:
            ““½,⁾ẇṭ»  |   - "", "Hello World"

```

# Answer
> 3 votes
# Befunge-93, 54 bytes

```
~"*"-_~1+#^_"dlroW olleH">:#,_@.%*2**:*::*88:*`0:?1#+<

```

Try it online!

**Annotated:**

```
~"*"-                      _                ~1+                   #^_        "dlroW olleH">:#,_    @      .%*2**:*::*88:   *`0:             ?1#+<
Compare first      If equal, go right       Compare second       If equal,        Output          Exit    Modulo by 2^31   If less than      Add 1
character to       Otherwise, go left       character to       loop forever   "Hello World"                 and output     0, multiply     a random amount
'*'                and wrap around          -1 (EOF)                                                                         by 0            of times

```

The randomness is not uniform. At each increment there is a 50% chance to stop incrementing.

# Answer
> 3 votes
# PowerShell, ~~60~~, 56 bytes

```
switch($args){*{'Hello World'}' * '{random}*+*{for(){}}}

```

Pretty dumb version, the only golfing technique here is omitting `Get-` in `Get-Random`.

**UPD.** Stripped down to 56 bytes by removing quotes, thanks to veskah!

# Answer
> 3 votes
# ///, 72 bytes

```
/+*/+*// */a random number between 0 and 0//*/"Hello World"/

```

Try it online!

Here I go again, adding another cheating entry. Was I really going write my own pseudo-random generator just for this though... and in **///**?!

Instead, I interpreted the `Print` instruction very literally, as a good minion should. Everything after `Print` is outputted:

### `*` Prints "Hello World"

> `*``"Hello World"`, yes, even with the quotation marks. Otherwise, I'd admit to being aware of the quotation-marks-denote-literal-string convention, which wasn't explicitly stated in the question, and doesn't exist in the language with which I'm submitting. And then I wouldn't be able to cheat with the *"Print a random number"* part. So, I'm feigning ignorance... Shhh, don't tell!

### ` * ` Prints a random number between 0 and 2,147,483,647

> `*``a random number between 0 and 0`. Lucky for me, although they didn't add the whole non-deterministic, different-number-every-time shtick in the rules, they did say *"if our language's integer maximum is smaller than 2,147,483,647"* we can use our language's *"integer maximum"* instead, so I did... There *are* no integer types in **///**, only strings. So the integer maximum is `0`, sort of...
> Well, it shaves off a few bytes!

### `*+*` Runs Forever

> `*+*`. There's no `Print` instruction in this one so I can interpret it like a normal human. Replacing a pattern with itself (or another string containing itself), is the standard way to loop forever, and it's as succinct as it gets!

### Note

To golf it a bit, **///** looks for `+*` & ` *` rather than the whole thing. This works just as well. For the infinite loop, nothing ever prints because the replacing never stops, so you'll never find out that it's prepending an infinitely long list of `*` to the beginning every time it replaces. As for printing 'a random number,' we just don't replace one of the spaces, leaving a trailing space at the end of the output. Luckily, this hurts no one and is not noticeable. Plus, how's an ignoramus like me to know how many of the trailing spaces at the end of the `Print` instruction, until the margin, were on purpose :p

# Answer
> 2 votes
# Brachylog, ~~26~~ 23 bytes

```
l₃∈&hṢ∧2^₃₁-₁ṙw∨Ḥ⊇ᶠ³⁶tw

```

Try it online!

Takes the program as a string through the input variable, and ignores the output variable. Heavily exploits the guarantee that the input is only ever one of the three valid programs: any length-three input will behave like either `" * "` or `"*+*"` depending on whether or not the first character is a space, and any other input will behave like `"*"`.

```
l₃                         The input has length 3
  ∈                        and is an element of something,
   &h                      and the input's first element
     Ṣ                     is a space
  ∈                        (if not, try some other thing it's an element of),
      ∧2^₃₁-₁              so take 2,147,483,647 and
             ṙw            print a random number between 0 and it inclusive.
               ∨           If the input's length isn't 3,
                Ḥ⊇ᶠ³⁶tw    print the 36th subsequence of "Hello, World!".

```

# Answer
> 2 votes
# Perl 5 `-p`, ~~43~~ 39 bytes

```
$_=/ /?0|rand~0:/\+/?redo:"Hello World"

```

Try it online!

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 71 bytes

```
s=>{for(;s=="*+*";);return"*"==s?"Hello World":new Random().Next()+"";}

```

Try it online!

# Answer
> 2 votes
# Ruby `-n`, 47 bytes

```
puts~/ /?rand(1<<31):~/\+/?loop{}:"Hello World"

```

Try it online!

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

```
#/.{"*"->"Hello World"," * "->RandomInteger[2^31-1],_:>0~Do~∞}&

```

Try it online!

# Answer
> 2 votes
# Java (JDK), 83 bytes

```
s->{for(s=s.intern();s=="*+*";);return"*"==s?"Hello World":(-1>>>1)*Math.random();}

```

Try it online!

# Answer
> 2 votes
# PHP, 51 bytes

```
for(;'*'<$l=$argn[1];);echo$l?rand():'Hello World';

```

Try it online! (Hello World)

Try it online! (Random Number)

Try it online! (Infinite Loop)

Takes second character of input which can be `''`, `'*'` or `'+'`. In case of `'+'` the `'*'<'+'` will be true and the loop will be infinite, else, after the loop, "Hello World" or a random number is shown. The `rand()` automatically outputs a number between 0 and `getrandmax()` which uses defined `RAND_MAX` in standard C library and by default is `2147483647` on most platforms/environments, including TIO.

# Answer
> 2 votes
# APL (Dyalog Unicode), 39 bytesSBCS

Anonymous prefix lambda.

```
{'+'∊⍵:∇⍵⋄' '∊⍵:⌊2E31×?0⋄'Hello World'}

```

Try it online!

`{` "dfn";  is the argument:

`'+'∊⍵:` if plus is a member of the argument:

`∇⍵` tail recurse on argument

`' '∊⍵` if space is a member of the argument:

`?0` random float (0–1)

`2E31×` scale to (0–2³¹)

floor

`'Hello World'` else return the string

# Answer
> 2 votes
# 05AB1E, 21 bytes

```
'*KgDi[ë<ižIL<Ωë”Ÿ™‚ï

```

Try it online. (NOTE: The random buildin is pretty slow with big lists, so it might take awhile before the result is given.)

**Explanation:**

```
'*K           '# Remove all "*" from the (implicit) input
   g           # Get the length of what's remain (either 0, 1, or 2)
    D          # Duplicate this length
     i         # If the length is exactly 1:
      [        #  Start an infinite loop
     ë<i       # Else-if the length is 2:
        žI     #  Push builtin 2147483648
          L    #  Create a list in the range [1,2147483648]
           <   #  Decrease each by 1 to make the range [0,2147483647]
            Ω  #  Pop and push a random value from the list
               #  (after which the top of the stack is output implicitly as result)
     ë         # Else:
      ”Ÿ™‚ï    #  Push dictionary string "Hello World"
               #  (after which the top of the stack is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `”Ÿ™‚ï` is `"Hello World"`.

# Answer
> 2 votes
# Pyth, 32 bytes

```
It/Jw\*#;?tlJOhC*4\ÿ"Hello World

```

Try it online!

## Explanation (Python-ish)

```
I                                   # if
  /Jw\*                             #    (J:=input()).count("*"))
 t                                  #                             - 1:
       #;                           #     try: while True: pass;except: break;
         ?                          # if (ternary)
           lJ                       #    len(J):
             O                      #     randInt(0,                    )
               C                    #                int(     , 256)
                *4\ÿ                #                    4*"ÿ"
              h                     #                                + 1
                    "Hello World    # else: (implicitly) print "Hello World"

```

# Answer
> 2 votes
# JavaScript, 62 Bytes, no infinite recursive

```
s=>s[1]?eval("while(s>'!');Math.random()*2**31"):'Hello World'

```

# Answer
> 2 votes
# JavaScript (V8), 79 bytes

-2 bytes thanks VFDan

```
s=>eval([`"Hello World"`,`Math.random()*2**31|0`,`for(;;);`][s.lastIndexOf`*`])

```

Try it online!

# Answer
> 2 votes
# Pip, ~~39~~ 35 bytes

```
IaQ'*P"Hello World"EIsQ@aPRRmE{T0a}

```

Try it online!

Simple if else based program, prints random integer between 0 and 1000.

# Answer
> 2 votes
# Vyxal, 16 bytes

```
×=[kh|tð=[k×ʀ℅|{

```

Try it Online! The `5` flag is just so that you don't have to wait as long for it to timeout. Even at the default 60 second timeout, this times out on  `*` , but you can see that it works by replacing  with a smaller number.

Currently, this beats all other answers.

Explanation:

```
                  # Implicit input
×=[               # If input = "*":
   kh             #   Push "Hello World"
     |tð=[        # Else if last character of input = " ":
          k×      #   Push 2147483648
            ʀ     #   Range [0, 2147483648]
             ℅    #   Random integer from range
              |   #     Else:
               {  #       While True:  (Infinite loop)
                  # Implicit output

```

# Answer
> 1 votes
# Charcoal, 30 bytes

```
Ｗ№θ*Ｆ⁼θ*≔Hello Worldθ∨θＩ‽Ｘ²¦³¹

```

Try it online! Link is to verbose version of code. Abuses Charcoal's default input format which splits on spaces if there is only one line, thus the random number input actually looks like three inputs. Explanation:

```
Ｗ№θ*

```

Repeat while the first input contains a `*`.

```
Ｆ⁼θ*

```

If the first input is a `*` only...

```
≔Hello Worldθ

```

... then replace it with `Hello World`, thus causing the loop to terminate. `*+*` doesn't get replaced, resulting in an infinite loop.

```
∨θ

```

If the first input is not empty then output it.

```
Ｉ‽Ｘ²¦³¹

```

But if it is empty then output a random integer in the desired range.

# Answer
> 1 votes
# Add++, 78 bytes

```
z:"Hello World"
`y
xR2147483647
x:?
a:"*"
b:" * "
c:"*+*"
Ix=a,Oz
Ix=b,O
Wx=c,

```

Try it online!

## Explanation

```
z:"Hello World"	; Set z = "Hello World"
`y		; Set y as the active variable
xR2147483647	; Set y to a random number between 0 and 2147483647
x:?		; Set x to the input
a:"*"		; Set a = "*"
b:" * "		; Set b = " * "
c:"*+*"		; Set c = "*+*"
Ix=a,		; If x == a then...
	Oz	;	...output z
Ix=b,		; If x == b then...
	O	;	...output y
Wx=c,		; While x == c then...
		;	...do nothing

```

# Answer
> 1 votes
# Commodore BASIC (VIC-20, C64, TheC64Mini etc) - 170 tokenize BASIC bytes

```
 0a%=32767:goS9:b$=leF(b$,len(b$)-1):ifb$="*"tH?"hello world
 1ifb$=" * "tH?int(rN(ti)*a%)
 2ifb$="*+*"tHfOi=.to1:i=.:nE
 3end
 9b$="":fOi=.to1:geta$:i=-(a$=cH(13)):b$=b$+a$:?a$;:nE:reT

```

I think to do this more accurately, I'll have to delve into the weird world of 6502 assembly language, but this is a first draft.

First point, the `INPUT` keyword in Commodore BASIC ignores white spaces, so the sub-routine at line `9` is a quick-and-dirty way to accept keyboard entries including spaces.

Second point, Commodore BASIC integers have a range of 16-bit signed, so -32768 to +32767 source \- so I've kept the random number generated to 0 - 32767 inclusive

# Answer
> 1 votes
# Wren, ~~143~~ 135 bytes

I am not a good golfer... The RNG generates the same value each time because it is a pseudo-random number generator.

```
Fn.new{|a|
import"random"for Random
if(a=="*+*"){
while(1){}
}else System.write(a[0]==" "?Random.new(9).int((1<<31)-1):"Hello World")
}

```

Try it online!

# Answer
> 1 votes
# Kotlin, 78 bytes

```
{print(if(it<"*")(0..2147483647).random()else{while(it>"*"){}
"Hello World"})}

```

Try it online!

# Answer
> 1 votes
# VBScript, 147 bytes

```
Sub m(s)
randomize:i=0
if s="*" then msgbox "Hello World"
if s=" * " then msgbox int(2147483647*Rnd)
if s="*+*" then
do
loop while 1
end if
end sub

```

# Answer
> 0 votes
# Crystal, 75 bytes

```
puts case gets;when"*";"Hello World"when/\+/;loop{}else;rand 2147483647;end

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 21 bytes

```
['*›_#}gi„Ÿ™‚ï™ëžIL<Ω

```

Try it online!  `*`  times out on TIO as the code generates the list `[1, 2, 3, ..., 2147483648]`, subtracts 1 from each element, and picks a random element from the list. This is required as the only sources of randomness in 05AB1E are `Ω`/`.R` (random pick) and `.r` (random shuffle), but no pure RNGs.

```
['*›_#}gi„Ÿ™‚ï™ëžIL<Ω  # full program
     #                 # break out of...
[                      # infinite loop...
     #                 # if...
                       # implicit input...
   ›                   # does...
    _                  # not...
   ›                   # come after...
 '*                    # literal...
   ›                   # in lexicographical order
      }                # end infinite loop
        i              # if...
       g               # length of...
                       # implicit input...
        i              # is 1...
         „Ÿ™‚ï         # then push "hello world"...
              ™        # in title case
               ë       # else...
                    Ω  # pick a random element from...
                  L    # [1, 2, 3, ...,
                žI     # ..., 2147483648]...
                       # (implicit) with each element...
                   <   # decremented
                       # implicit output

```

---
Tags: code-golf, random, interpreter, hello-world
---


title: Golf Your Favorite Minecraft Tool

text:
# Question
Title: Golf Your Favorite Minecraft Tool
In Minecraft, the default item textures are all reasonably simple 16×16 pixel images, which makes them seem ideal for golfing.

Below are simplified textures of the five "core" diamond tools in Minecraft: pickaxe, shovel, axe, sword, and hoe.

**The images shown are enlarged to show their detail. Click on an image to view its correctly sized 16×16 pixel version.**

To make golfing easier, I've modified each of them from the originals to only use the five same 24-bit RGB colors:

* `R=75 G=82 B=73` for the background.
* `R=51 G=235 B=203` for the diamond tool heads.
* `R=14 G=63 B=54` for the diamond outlines.
* `R=137 G=103 B=39` for the wooden handle core.
* `R=40 G=30 B=11` for the wooden handle outlines.

Choose your favorite tool out of the five and write a program that outputs its simplified 16×16 pixel texture in any common lossless truecolor image format (such as `bpm`, `png`, `ppm`, etc.).

So, for example, if you chose the axe, you would write a program that outputs this image:

No input should be taken and a web connection should not be required. The image can be output as a file with the name of your choice, or the raw image file data can be output to stdout, or you can simply display the image.

You only need to choose *one* of the five images. **The program that outputs any one of the five images in the fewest number of bytes is the winner.**

You may write programs for more than one of the images, but only the one with the minimum number of bytes counts towards your score. If there's a tie, the highest voted post wins.

---

*If you enjoy PPCG and play Minecraft, I invite you to come join our trial Minecraft server. Just ask in the dedicated chatroom.*

# Answer
# CJam, 119 bytes

```
'P3NGSGN255N]o67T"…vîþáy$<OW¥ÓNZ"256b9b~99T]2/e~W%"LRI?6jêÌ'
…f-":i3/f=F,_W%:)+{)/(\:~}%{G/({)S*S+oNo}%1>\:~+}G*

```

Try it online!

I've chosen the shovel.

This program prints a PPM file to STDOUT.

The basic idea is to unroll the image along antidiagonals and then use run-length encoding. With this technique, the shovel contains the fewest runs. For reference the number of runs per image (in the order given in the challenge) is:

```
{60, 26, 38, 43, 37}

```
> 6 votes

# Answer
# Minecraft 18w11a (.mcfunction), 757 bytes

```
fill ~ ~ ~ ~15 ~ ~15 ice
fill ~13 ~ ~13 ~7 ~ ~11 cyan_wool
fill ~12 ~ ~14 ~10 ~ ~8 cyan_wool
fill ~12 ~ ~13 ~10 ~ ~11 diamond_block
fill ~11 ~ ~12 ~9 ~ ~10 diamond_block
fill ~10 ~ ~11 ~8 ~ ~9 diamond_block
fill ~3 ~ ~4 ~1 ~ ~2 dirt
setblock ~3 ~ ~4 oak_planks
setblock ~2 ~ ~3 oak_planks
clone ~3 ~ ~4 ~1 ~ ~2 ~4 ~ ~5
setblock ~4 ~ ~5 oak_planks
setblock ~4 ~ ~7 ice
setblock ~6 ~ ~5 ice
clone ~6 ~ ~5 ~4 ~ ~7 ~7 ~ ~8
setblock ~9 ~ ~10 diamond_block
setblock ~4 ~ ~4 dirt
setblock ~3 ~ ~5 dirt
setblock ~7 ~ ~7 dirt
setblock ~6 ~ ~8 dirt
setblock ~1 ~ ~2 ice
fill ~12 ~ ~9 ~12 ~ ~8 ice
setblock ~11 ~ ~8 ice
fill ~8 ~ ~13 ~7 ~ ~13 ice
setblock ~7 ~ ~12 ice
fill ~ ~ ~ ~15 ~ ~15 light_gray_concrete replace ice
fill ~ ~ ~ ~9 ~ ~10 dark_oak_bark replace dirt

```

Of course someone had to answer the question with Minecraft. Place answer inside of a datapack, and run with `/function <packname>:<filename>`. The shovel is drawn relative to you in the +X and +Z direction. Colors are wrong but I'll count that as a language limitation ;)

But the shovel is actually made out of wood and diamonds!!!!

## Output
> 12 votes

# Answer
# JavaScript ES6, 353 bytes

```
document.write(`<p style="width:1px;height:1px;box-shadow:${'931a31b31841940a40b40c41951a51b50c50d51e53f52b61c60d60e62f63c73d70e70f71b83c82d83e81a93b92c939a3aa2ba38b39b2ab37c38c29c36d37d28d35e36e27e34f35f26f34g35g3'.replace(/.../g,e=>(p=parseInt)(e[0],17)+`px ${p(e[1],17)}px 0 #${['33EBCB','0E3F36','896727','281E0B'][e[2]]},`)}9px 9px 0 8px #4B5249"`)

```

This heavily abuses CSS3 box-shadows to create a pixelized version of the image, in this case the Minecraft hoe. The Stack Snippet below uses ES5 for easy testing and is somewhat ungolfed (You'll have to zoom in to see it well).

```
s='931a31b31841940a40b40c41951a51b50c50d51e53f52b61c60d60e62f63c73d70e70f71b83c82d83e81a93b92c939a3aa2ba38b39b2ab37c38c29c36d37d28d35e36e27e34f35f26f34g35g3'.replace(/.../g,function(e){
  return parseInt(e[0],17)+'px '+parseInt(e[1],17)+'px 0 #'+['33EBCB','0E3F36','896727','281E0B'][e[2]]+','
})
document.write('<p style="width:1px;height:1px;box-shadow:'+s+'9px 9px 0 8px #4B5249"')
```
> 8 votes

# Answer
# 05AB1E, ~~113~~ 97 bytes

*-16 by using RLE (run-length encoding) for the color palette indices.*

```
„P3žvD₅•P{¡æjž²+JGÀ‰íÔñ•Ƶ‡в3ô•N…ý~îc|\мï¶„Ä^€¿^•5в¦•RθÅª`<≠cλS²bÖ"₁Þ@„ÉI¬5øëY4ÀΘØ¥P@û h•29вÅΓè˜»»

```

Try it online! Beats all other answers. Outputs a plain PPM of a diamond hoe.

**Note:** The first `»` can be a `)` (or a , `ð`, or `õ`) to output the image data separated by spaces: Try it online! However, in the official PPM Format Specification, under *Plain PPM*, it states:

> * No line should be longer than 70 characters.

It still renders properly, but is not recommended.

The first `»` can also be a ``` with no change in functionality: Try it online!

### Pure GIF compression, ~~109~~ 107 bytes

```
•+Ùι1Ù³œ¤∞4ûи„ĆQ´ηÏzεÝ₅¼úΣ¨ü6Ó…Ï,È–ð:<û∞¢Þ§α»«¥<çp:Ù“ζÞ¢ó‡lÿнδßiÌ$}ªiƒ*₅xΛxJ=yh‹×м’’®']!JÍ¦Z¹JQc›Vàÿ¸Ìм•h2ô

```

Try it online! Outputs as a list of hexadecimal codepoints.

```
•...•h2ô  # trimmed program
•...•     # 121686424391392225557581524495943776461362082974476220323034665137613008241067075561955081975776948192923502794622971144661356950543760600319115998403445050769039958830830234731371315671091547736084642764295720991029129326629299863698388004372539...
     h    # in hexadecimal...
       ô  # split into pieces of length...
      2   # literal
          # implicit output

```
> 4 votes

# Answer
# Node.JS using jimp, ~~393~~ ~~377~~ 376 bytes

377, 376 thanks to Makonede

```
new(require('jimp'))(16,16,1263684095,(e,i)=>{i.z=i.setPixelColor;i.z(x=673057791,2,12);i.z(x,4,14);i.z(d=871091199,13,3);for(j=0;j<8;j++){i.z(w=2305239039,3+j,13-j);i.z(x,2+j,13-j);i.z(x,3+j,14-j)}for(j=0;j<3;j++){i.z(e=239023871,11+j,2);i.z(e,14,3+j);i.z(e,8+j,5-j);i.z(d,9+j,5-j);i.z(d,10+j,5-j);i.z(d,10+j,6-j);i.z(d,11+j,6-j);i.z(d,11+j,7-j);i.z(e,11+j,8-j)}i.write('')})

```

I'm not sure if this one is allowed as it uses a separate library for processing the image.

Uses hex colors in decimal, sets `i.s` to `i.setPixelColor` to save bytes, sets color variables as it's first used
> 3 votes

# Answer
## Python 3, 483 bytes

I chose to make the sword

```
from PIL import Image as IG, ImageColor as IC
s=IG.new('RGB',(16,16))
w='#6b6727'
b='#4b5249'
d='#33ebcb'
a='#0e3f36'
n='#281e0b'
t=b*13+a*3+b*12+a+d*2+a+b*11+a+d*3+a+b*10+a+d*3+a+b+b*9+a+d*3+a+b*2+b*8+a+d*3+a+b*3+b*2+a*2+b*3+a+d*3+a+b*4+b*2+a+d+a+b+a+d*3+a+b*5+b*3+a+d+a+d*3+a+b*6+b*3+a+d+a+d*2+a+b*7+b*4+a+d+a*2+b*8+b*3+n+w+a+d*2+a+b*7+b*2+n+w+n+b+a*2+d+a+b*6+a*2+w+n+b*4+a*2+b*6+a+d+a+b*13+a*3+b*13
s.putdata([IC.getrgb(t[i:i+7]) for i in range(0,len(t),7)])
s.save('s.png','PNG')

```

here is the output:

I created a string for each color, and combined them to get a string of hexadecimal numbers. Then I used the python image library to convert that string into an image.
> 2 votes

# Answer
# GIF, 102 bytes

Hexdump:

```
00000000: 4749 4638 3961 1000 1000 7000 002c 0000  GIF89a....p..,..
00000010: 0000 1000 1000 824b 5249 0e3f 3633 ebcb  .......KRI.?63..
00000020: 281e 0b89 6727 0000 0000 0000 0000 0003  (...g'..........
00000030: 3308 babc f12d 8220 4490 8cd6 8b67 b59d  3....-. D....g..
00000040: b785 1a98 71a2 9981 25da 506d 078f a4e5  ....q...%.Pm....
00000050: 4a03 a1dd 4c3e 4cb0 c883 f073 f082 21c5  J...L>L....s..!.
00000060: 8327 4900 003b                           .'I..;

```

Renders as:
> 1 votes

---
Tags: code-golf, graphical-output, kolmogorov-complexity, game
---


title: Write an interpreter for "interpreter"

text:
# Question
Title: Write an interpreter for "interpreter"
I just created a language on the spot, and it's called "interpreter". Called as such because the only valid word is "interpreter"! A sample program in "interpreter" looks like this:

```
interpreter interpreterinterpreter interpreterinterpreterinterpreter interpreterinterpreterinterpreterinterpreter interpreterinterpreterinterpreterinterpreterinterpreter interpreterinterpreterinterpreterinterpreterinterpreterinterpreter

```

It may look meaningless, but the language works like:

* `interpreter` initializes the accumulator to zero.
* `interpreterinterpreter` adds one to the accumulator.
* `interpreterinterpreterinterpreter` subtracts one from the accumulator.
* `interpreterinterpreterinterpreterinterpreter` multiplies the accumulator by 2.
* `interpreterinterpreterinterpreterinterpreterinterpreter` divides the accumulator by 2.
* `interpreterinterpreterinterpreterinterpreterinterpreterinterpreter` outputs the accumulator.

## Rules

* Standard loopholes are forbidden.
* Shortest program in **bytes** wins.
* Your program should work for all test cases.
* You may assume that all code entered is valid.
* The first command will always be `interpreter`.
* There will always be a single space between each command.
* Floating point division, not integer division.
* Trailing newlines are allowed.

## Testcases

```
interpreter interpreterinterpreter interpreterinterpreterinterpreterinterpreterinterpreterinterpreter -> 1
interpreter interpreterinterpreter interpreterinterpreter interpreterinterpreterinterpreterinterpreter interpreterinterpreterinterpreter interpreterinterpreterinterpreterinterpreterinterpreterinterpreter -> 3
interpreter interpreterinterpreterinterpreterinterpreterinterpreter interpreterinterpreter interpreterinterpreterinterpreterinterpreterinterpreterinterpreter -> 1
interpreter interpreterinterpreter interpreterinterpreter interpreterinterpreterinterpreterinterpreterinterpreterinterpreter interpreterinterpreterinterpreter interpreterinterpreterinterpreterinterpreterinterpreterinterpreter interpreter interpreterinterpreter interpreterinterpreterinterpreterinterpreterinterpreterinterpreter -> outputs 2, then outputs 1, then outputs 1

```

# Answer
> 7 votes
# JavaScript (V8), 71 bytes

```
s=>s.split` `.map(i=>(n=i.length%6)?s=[,s/2,s*2,s-1,s+1,0][n]:print(s))

```

Try it online!

### How?

The length of an *interpreter* instruction is \\$11\times k,\\:1\le k \le 6\\$, which gives \\$\[11,22,33,44,55,66\]\\$. When applying a modulo \\$6\\$, this maps to \\$\[5,4,3,2,1,0\]\\$. This is shorter than dividing by \\$11\\$ and allows us to easily identify the *output* instruction (size \\$66\\$, mapped to \\$0\\$) which behaves differently from the other ones.

---

# JavaScript (V8), 80 bytes

This version is also based on the length of the instruction modulo \\$6\\$ but doesn't use any lookup table. It updates the accumulator with a single statement, using arithmetic and bitwise operations.

This is rather pointless in JS but does save a few bytes in C (as opposed to a chain of ternary operators).

```
s=>s.split` `.map(i=>(n=i.length%6)?A=A*(6&9/n|n<2)/2+(3>>n-3^2)-2:print(A),A=0)

```

Try it online!

```
           | n =        | multiply by:  | add:
 operation | length % 6 | (6&9/n|n<2)/2 | (3>>n-3^2)-2
-----------+------------+---------------+--------------
 clear     |      5     |       0       |      0
 increment |      4     |       1       |      1
 decrement |      3     |       1       |     -1
 double    |      2     |       2       |      0
 halve     |      1     |      0.5      |      0

```

# Answer
> 3 votes
# C (gcc), ~~113~~ \\$\cdots\\$ ~~113~~ 111 bytes

Saved ~~3~~ 6 bytes thanks to the man himself Arnauld!!!
Added 6 bytes to accommodate floating-point division. Saved 2 bytes thanks to ceilingcat!!!

```
float a;c;f(char*s){for(;*s;c?a=a*(6&9/c|c<2)/2+(3>>c-3^2)-2:printf("%f ",a),++s)for(c=1;*++s&&*s-32;c=++c%6);}

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~18~~ 17 bytes

```
#€g"=;·<>0"sè».Võ

```

Try it online!

+2 bytes thanks to a bug, corrected by Makonede

-1 byte thanks to Command Master!

## How it works

```
#€g"=;·<>0"sè».Võ - Program. Push the input I to the stack
#                 - Split I on spaces
 €g               - Lengths of €ach
   "=;·<>0"       - Push "=;·<>0"
           s      - Swap, moving the lengths to the top of the stack
            è     - Index into string, 0-based and modularly
             »    - Join by newlines
              .V  - Run as 05AB1E code
                õ - Push the empty string

```

This takes a similar approach to my Jelly answer, translating into 05AB1E then running. This only beats Jelly because the increment commands can go in strings in 05AB1E, but not in Jelly

We don't need to bother with any syntax nonsense to reset the accumulator in 05AB1E. Instead, as all the commands operate on the top value, we just push a 0 to the top of the stack

| interpreter command | Equivalent 05AB1E command | What it does in 05AB1E |
| --- | --- | --- |
| `interpreter` | `0` | Pushes `0` to the ToS (top of stack) |
| `interpreterinterpreter` | `>` | Increments the ToS |
| `interpreterinterpreterinterpreter` | `<` | Decrements the ToS |
| `interpreterinterpreterinterpreterinterpreter` | `·` | Doubles the ToS |
| `interpreterinterpreterinterpreterinterpreterinterpreter` | `;` | Halves the ToS |
| `interpreterinterpreterinterpreterinterpreterinterpreterinterpreter` | `=` | Prints the ToS without popping it |

We push an empty string at the end to prevent implicit output. If nothing has been output by the transpiled interpreter code, 05AB1E would output the ToS. We push the empty string so that if no output has been produced, 05AB1E outputs the empty string instead

# Answer
> 3 votes
# Vyxal `rDO`, 13 bytes

```
⌈vL`…½d‹›0`İĖ

```

Try it Online!

Vyxal port of @caird coinheringaahing’s 05AB1E answer.

Explanation:

```
               # Implicit input
⌈              # Split on " "
 vL            # Length of each command
   `…½d‹›0`    # Push "…½d‹›0" 'D' flag - treat as raw string
           İ   # Index into string
            Ė  # Exec as Vyxal code
               # 'O' flag - disable implicit output

The commands in `…½d‹›0`:
… - Print without popping
½ - Halve
d - Double
‹ - Decrement
› - Increment
0 - Push 0

```

# Answer
> 2 votes
# Python 3, ~~138~~ bytes

Easy translation of the *interpreter language* instructions:

```
for i in[len(o)/11for o in input().split(' ')]:
 if i==1:a=0
 if i==2:a=a+1
 if i==3:a=a-1
 if i==4:a=a*2
 if i==5:a=a/2
 if i==6:print(a)

```

Try it online!

In the first line:

1. takes the input
2. split the instructions separated by a space
3. divide by 11 (the lenght of the base word `interpreter`) to get the corresponding operation

The subsequent `if` execute the operations on the accumulator.

*EDIT:* theoretical improvements, code not modified (see version 2). Anyway, thanks for the suggestions!

*-4 bytes thanks to @expressjs123*

*-3 bytes thanks to @ElPedro*

---

**VERSION 2**

# Python 3, ~~97~~ ~~96~~ 93 bytes

Improved the selection of the instructions simply by using list slicing.

*-41 bytes compared to original version.*

*-1 byte thanks to @ElPedro*

*-3 bytes thanks to @Zaelin Goodman*

```
a=0
for i in[len(o)//11for o in input().split()]:
 a-=[a,-1,1,-a,a/2,0][i-1]
 if i>5:print(a)

```

Try it online!

# Answer
> 2 votes
# PHP, ~~128~~ ~~105~~ ~~90~~ 86 bytes

```
foreach(explode(' ',$argn)as$v)($i=strlen($v)%6)?$c-=[0,$c/2,-$c,1,-1,$c][$i]:print$c;

```

Try it online!

~~Actually counting the number of parts split by `p` rather than counting `interpreter`, so that any word that contains "p" would work.~~

EDIT: saved 23 bytes by using an array (inspired by other answers)

EDIT 2: another 15 bytes with @Arnauld the Great's modulo 6. Basically a port of his answer now

EDIT3: 4 bytes less with an array of values to subtract instead of an array to assign

# Answer
> 2 votes
# Bash, ~~120~~ 71 bytes

```
o=(. =0 ++ -- *=2 /=2)
for i;do
((x${o[n=${#i}/11]},n-6))||echo $x
done

```

Try it online!

### Credits

* Saved 4 bytes from both answers thanks to @Neil
* Saved 49 bytes thanks to @DigitalTrauma

# Answer
> 1 votes
# PHP, 80 bytes

```
foreach(explode(' ',$argn)as$v)$a-=[$a/2,-$a,1,-1,$a][strlen($v)%6-1]??!print$a;

```

Try it online!

**Explanation**

```
$a                 // accumulator
-=                 // subtract operation result and assign to accumulator
[$a/2,-$a,1,-1,$a] // array of operations (divide, multiply, subtract, add, reset)
[strlen($v)%6-1]   // modulo 6 of command length, minus 1
                   // this way the print command (-1) will not be present in array
??                 // array key does not exist?
!print$a;          // print accumulator and toggle the boolean value of print's return
                   // toggle is required, because print always returns 1
                   // and we don't want to modify accumulator value, so !1 == 0

```

**Credits**

# Answer
> 1 votes
# Jelly, 18 bytes

```
ḲẈị“HḤ“øȮ”j⁾’‘¤Vṛ“

```

Try it online!

## How it works

```
ḲẈị“HḤ“øȮ”j⁾’‘¤Vṛ“ - Main link. Takes a string I on the left
Ḳ                  - Split I at spaces
 Ẉ                 - Get the length of each section
              ¤    - Group into a nilad:
   “HḤ“øȮ”         -   [["H", "Ḥ"], ["ø", "Ȯ"]]
           ⁾’‘     -   ["’", "‘"]
          j        -   Join; ["H", "Ḥ", "’", "‘", "ø", "Ȯ"]
  ị                - Index into the string, modularly and 1-indexed
               V   - Execute as Jelly code
                 “ - Yield the empty string
                ṛ  - Replace with the empty string to suppress automatic output

```

This program translates interpreter into Jelly and then runs it as Jelly code. First, only the lengths of each command actually matter. The lengths are `[11, 22, 33, 44, 55, 66]`, which are unique modulo 6. The commands are transliterated as follows:

| interpreter command | Length | Length mod 6 | Jelly command |
| --- | --- | --- | --- |
| `interpreter` | 11 | 5 | `ø` |
| `interpreterinterpreter` | 22 | 4 |  |
| `interpreterinterpreterinterpreter` | 33 | 3 |  |
| `interpreterinterpreterinterpreterinterpreter` | 44 | 2 |  |
| `interpreterinterpreterinterpreterinterpreterinterpreter` | 55 | 1 | `H` |
| `interpreterinterpreterinterpreterinterpreterinterpreterinterpreter` | 66 | 0 | `Ȯ` |

As Jelly uses modular indexing, we don't need to bother to modulo the lengths, we can just go ahead and into the command list.

Most of these commands are pretty obvious and are direct translations from the spec (e.g.  is Jelly's increment command,  is double etc.). However, `ø` is slightly different (and I think this is the only time I've every used it).

`ø` is a syntax command that tells Jelly to begin a new niladic chain. This basically tells Jelly to throw away everything before it and to reset, using `0` as the argument for the new command. As we're outputting as we go, its actually perfectly fine to "throw away" the previous commands, because they're no longer relevant.

# Answer
> 0 votes
# Python 3, ~~84~~ 82 bytes

```
n=0
for c in input().split():l=len(c)%10;n+=[-n,1,-1,n,-n/2,0][l-1];l==6==print(n)

```

Try it online!

-2 bytes Oliver Ni

# Answer
> 0 votes
# Charcoal, 31 bytes

```
Ｆ⪪Ｓ ≡№ιi¹≔⁰θ²≦⊕θ³≦⊖θ⁴≦⊗θ⁵≦⊘θ⟦Ｉθ

```

Try it online! Explanation:

```
Ｆ⪪Ｓ

```

Split the input on spaces and loop over each word.

```
≡№ιi

```

Count the number of `i`s in each word.

```
¹≔⁰θ²≦⊕θ³≦⊖θ⁴≦⊗θ⁵≦⊘θ⟦Ｉθ

```

Perform the appropriate operation on the accumulator depending on the number of `i`s.

Note that a `switch` is shorter than looking up the results in an array as I don't have to initialise the accumulator.

# Answer
> 0 votes
## Batch, 206 bytes

```
@set/ps=
@set t=@set "s=
%t%%s:nterpreter=%
%t%%s: =&set/an%
%t%%s:set/aniiiiii=call:c%
%t%%s:iiiii=/=2%
%t%%s:iiii=*=2%
%t%%s:iii=-=1%
%t%%s:ii=+=1%
%t%%s:i==0%
@set/an%s%
@exit/b
:c
@echo %n%

```

Takes input on STDIN. Works by performing substitutions on the input string to produce Batch code which is then executed.

# Answer
> 0 votes
# Java, ~~137~~ 129 bytes

```
s->{var x=0d;int l;for(var w:s.split(" ")){if((l=w.length()/11)==6)System.out.println(x);x-=new double[]{x,-1,1,-x,x/2,0}[l-1];}}

```

Try it online!

*Saved 8 bytes thanks to branboyer.*

# Answer
> 0 votes
# PowerShell, 83 -\> 73 -\> NOW 59 bytes

```
$args|% Le*|%{,$a*!($_%6);$a-=(0,($a/2),-$a,1,-1,$a)[$_%6]}

```

Try it online!

Thanks to @mazzy and @ZaelinGoodman

# Answer
> 0 votes
# Bash \+ GNU utils, 89

Transpiles to `dc`, then interprets:

```
sed -r 's/\S{11}/x/g;s/x{6}/p/g;s/x{5}/2\//g;s/x{4}/2*/g;s/xxx/1-/g;s/xx/1+/g;s/x/0/g'|dc

```

Try it online!

# Answer
> 0 votes
# Japt, 29 bytes

```
¸®=Êu6)?E=[,E/2EÑEÉEÄT]gZ:OpE

```

Try it

# Answer
> 0 votes
# YaBASIC, 130 bytes

```
dim c$(1)
n=split(i$,c$())
for j=1 to n
c=mod(len(c$(j)),6)
if c a=a*or(and(6,9/c),c<2)/2+xor(mod(3/2^(c-3),6),2)-2
if !c ?a;
next

```

A basic interpreter interpreter running in an interpreted Basic interpreter...

Try it online!

Well, thanks to Arnauld's infamous MOD 6 trick, I was able to compress this perfectly readable, easily maintained and expandable 134 byte program:

```
dim c$(1)
n=split(i$,c$())
for j=1 to n
c=len(c$(j))/11
if c=1 a=0
if c=2 a=a+1
if c=3 a=a-1
if c=4 a=a*2
if c=5 a=a/2
if c=6 ?a;
next

```

into the 130-byte bit of opaque confusion seen above! If I was gonna develop "interpreter" as a product, I know which code-base I'd start with, but really, I'd rather program in DeadFish...

# Answer
> 0 votes
# Perl 5 `-a`, 66 bytes

```
eval((0,'$a=0','$a++','$a--','$a*=2','$a/=2','say$a')[y/i//])for@F

```

Try it online!

# Answer
> 0 votes
# Stax, 12 bytes

```
î╜║µI*▄mß┘r>

```

Run and debug it

Who needs flags when *compression*? :P

---
Tags: code-golf, interpreter
---


# Question
Title: The longest consecutive traversal possible (number of edges)
A truck fleet dispatcher is trying to determine which routes are still accessible after heavy rains flood certain highways. During their trips, trucks must follow linear, ordered paths between `26` waypoints labeled `A` through `Z`; in other words, they must traverse waypoints in either standard or reverse alphabetical order.

The only data the dispatcher can use is the trip logbook, which contains a record of the recent successful trips. The logbook is represented as a list of strings, where each string (corresponding to one entry) has two characters corresponding to the trip origin and destination waypoints respectively.

If the logbook contains a record of a successful trip between two points, it can be assumed that the full path between those points is accessible. Note that logbook entries imply that both directions of the traversal are valid. For example, an entry of `RP` means that trucks can move along both `R --> Q --> P` and `P --> Q --> R`. Note that the trips `A --> B` and `C -> D` do not together imply that `B -> C` is usable. Entries can have the same character twice, such as `C -> C`, but this indicates no paths.

Given an array of logbook entries, your task is to write a function to return the length of the longest consecutive traversal possible; in other words, compute the maximum number of consecutive edges known to be safe. (In even more formal terms, compute the diameter of the largest tree on this graph.)

**Example**

For `logbook = ["BG", "CA", "FI", "OK"]`, the output should be `8`

Because we can get both from `A` to `C` and from `B` to `G`, we can thus get from `A` to `G`. Because we can get from `F` to `I` and access `I` from `G`, we can therefore traverse `A --> I`. This corresponds to a traversal length of `8` since `8` edges connect these `9` waypoints. `O` through `K` is a length `4` traversal. These two paths are disjoint, so no longer consecutive paths can be found and the answer is `8`.

---

**Guaranteed constraints:**

`1 ≤ logbook.length ≤ 100`,

`logbook[i].length = 2`,

`logbook[i][j] ∈ ['A'..'Z']`.

---

**Test Cases:**

`logbook: ["AZ"]` `Output:25`

`logbook: ["AB", "CD"]` `Output:1`

`logbook: ["BG", "CA", "FI", "OK"]` `Output: 8`

`logbook: ["KM", "SQ", "ON", "XM", "UK"]` `Output:13`

`logbook: ["XU", "WY", "ZD", "HH", "BK", "LG"]` `Output: 24`

`logbook: ["QR", "PC", "TK", "OE", "YQ", "IJ", "HB"]` `Output: 23`

`logbook: ["MG", "QQ", "JV", "IZ", "SQ", "PN", "TI", "NK"]` `Output: 19`

`logbook: ["II", "ZW", "CI", "DT", "IM", "II", "TR", "XO", "AL"]` `Output: 25`

---

The input will always be an array of strings, each of which has exactly two characters corresponding to the trip origin and destination waypoints respectively. The characters will always be letters, in a consistent case of your choice. The input will never contain more than 100 pairs.

Your program should output the **longest consecutive traversal possible** (number of edges) given the input.

This is so the shortest code in bytes wins

# Answer
# APL (Dyalog Unicode), 17 bytes

```
≢⍉↑⊆⍨∨/≠/∨⍀⎕a∘.=⎕

```

Try it online!
> 14 votes

# Answer
# APL (Dyalog Unicode), 39 bytes

```
{⌈/≢¨⊆⍨∊∨¨/{(⊂⍵){1 3 2≡⍋∊⍺[⍋⍺]⍵}¨⎕A}¨⍵}

```

Try it online!

-4 bytes thanks to ovs
-6 bytes thanks to following a similar approach to Jonah's J answer
-6 bytes thanks to a clever observation from ovs
> 5 votes

# Answer
# , 52 48 41 40 38 34 29 bytes

```
3 :'>./#;._1#.~:/"1+./\a.=/y'

```

Try it online!

Based on ngn's beautiful insight.

-5 thanks to Lynn for realizing an explicit verb would be shorter than a tacit one

This is a corrected answer after the clarification that `ABCD` should return 1, not 3.

## answer before clarification, 52 48 41 40 38 bytes

```
[:>./[:<:@#;._1@OR a.(+/\*+/\.)@e."1]

```

Input is a matrix whose rows are the pairs of strings like `AC`. For example, let's assume our input is:

```
AC
EB

```
* `a. ... e."1]` \- Is each ascii character an element of an input row? This returns a 0-1 matrix like:

```
                 A   C  at positions 65 and 67
                 v   v
  0 0 0 0 .... 0 1 0 1 0 0 ... 0
  0 0 0 0 .... 0 0 1 0 0 1 ... 0
                   ^     ^
                   B     E

```
* `(+/\*+/\.)` \- Applies to each row from last step. We'll look at happens to the first row. Create scan sums from both directions:

```
  0 0 0 0 .... 0 1 1 2 ... 2 2 2  <-- +/\
  2 2 2 2 .... 2 2 1 1 ... 0 0 0  <-- +/\.

```

and multiply them together `*`:

```
  0 0 0 0 .... 0 2 1 2 ... 0 0 0

```
* `[:...OR` Reduce resulting rows by OR:

```
  0 0 0 0 .... 0 1 1 1 1 1 ... 0

```
* `[:<:@#;._1` Split on zeroes, and take the length of each resulting segment of ones, minus 1 `<:@#`.
* `[:>./` Max

Try it online!
> 5 votes

# Answer
# , ~~61~~ ~~69~~ 65 bytes

```
for(i in scan(,""))F[(j=utf8ToInt(i)*2):j[2]]=1;max(rle(F)$l)%/%2

```

Try it online!

Unfortunately, edits made to the task specification broke the original answer :(

On the brighter side, the changes needed to fix it were not so drastic.

### Explanation

First, we use `utf8ToInt` to convert the characters to their byte values. Then, we fill the vector `F` with ones at the range of positions from start byte to end byte. R allows assigning to indices outside of existing range, and upon such assignment sets all preceding empty positions to `NA`. Finally, we take Run Length Encoding and return the length of the longest run. Conveniently, `rle` doesn't list all `NA` as a single long run, but rather as many runs of length 1.

In the original version, ranges such as `AB CD` became fused together:

```
...     A  B  C  D    ...
... 64 65 66 67 68 69 ...
... NA  1  1  1  1    ...

```

To resolve this, we simply multiply the range boundaries by 2, and thus gain a separator between adjacent routes when they don't overlap:

```
...      A       B       C       D  ...
... 129 130 131 132 133 134 135 136 ...
... NA   1   1   1  NA   1   1   1  ...

```

Finally, integer division by 2 gives the desired result.
> 4 votes

# Answer
# Haskell, 86 bytes

* -5 bytes thanks to kops for suggesting `fst$span(`elem`y)[a..]`.
* +8 bytes to comply with the updated challenge rules.

```
f x|y<-do[a,b]<-x;[a..pred b]++[b..pred a]=maximum[length.fst$span(`elem`y)[a..]|a<-y]-1

```

Try it online!

The function `f` takes the logbook `x` as input (as a list of two-character strings) and returns the longest possible traversal.

## How?

```
f x|                                -- f is the function that takes a logbook x
    y<-do[a,b]<-x;                  --   define y to be the concatenation for each "ab" in x
        [a..pred b]++[b..pred a]    --     of the two ranges [a..pred b] and [b..pred a] (one of which will be empty)
    =maximum[length.                -- f returns the maximum length
        fst$span(`elem`y)[a..]      --   of the longest range starting from a whose elements all belong to y
        |a<-y]                      --   where a is a character in y

```
> 4 votes

# Answer
# Ruby, ~~79~~ 71 bytes

```
->a{r=c=0
a.map{|i|r|=-1<<i.ord^-1<<i[1].ord}
(c+=1;r&=r*2)while r>0;c}

```

Try it online!

Ruby probably isnt' the best language for this bit twiddling approach, but I haven't seen it yet so it's worth posting. The idea is to take `-1` and shift it to the left according to each letter, then XOR it with the other letter in the pair. It's best explained with an example (ignore 64 zeroes missing to the right.)

```
B ->    ...1111111100
G ->    ...1110000000
XOR     ...0001111100

```

Thus there are 5 clear paths between `B` and `G`.

These are then combined by `OR`ing together.

At the end of `["BG", "CA", "FI", "OK"]` we have `r=111100111111110` (plus 64 trailing zeroes).

To find the longest run of `1`s, we now count the number of times `r` must be `AND`ed with `r*2` until `r` becomes zero. Each time we perform this operation, the length of each group of 1's is reduced by one.
> 3 votes

# Answer
# Retina, 71 bytes

```
A`(.)\1
%O`.
%T`L`_L`.$
\B
-
¶

~`.+
.+¶26$*¶Y`\_`L¶[$&]¶_
L`_+
O^`
\G_

```

Try it online! Takes a newline-separated list, but the test suite takes a comma-separated list for convenience. Explanation:

```
A`(.)\1

```

Delete identical pairs, as they have nothing to contribute (other than crashes).

```
%O`.

```

Sort each pair of letters into order.

```
%T`L`_L`.$

```

Decrement the second of each pair, as the ranges are effectively half-open intervals.

```
\B
-

```

Insert a `-` between each pair of letters.

Join all of the letter ranges together.

```
~`.+
.+¶26$*¶Y`\_`L¶[$&]¶_

```

Wrap the letter ranges in Retina code that replaces legal edges with `_`s, then evaluate that code.

```
L`_+

```

Keep only the runs of `_`s, discarding any remaining letters.

```
O^`

```

Sort the longest first.

```
\G_

```

Output its length.

Example of generated Retina code for the input `BG`, `CA`, `FI`, `OK`:

```
.+
26*
Y`\_`L
[B-FA-BF-HK-N]
_

```

Explanation:

```
.+
26*

```

Replace the ranges with 26 `_`s.

```
Y`\_`L

```

Cyclically transliterate the `_`s to uppercase letters.

```
[B-FA-BF-HK-N]
_

```

Replace all the legal edges with `_`s.
> 2 votes

# Answer
# Charcoal, 16 bytes

```
ＩＬ⌈⪪⭆α⬤θ⊖ΣＥλ‹ιν1

```

Try it online! Link is to verbose version of code. Explanation: For each uppercase letter, compare it against all of the logs to see whether it precedes neither or both entries, resulting in a string of exclusions e.g. `00000000110000111111111111` for an input of `BG`, `CA`, `FI`, `OK`. Split that string on `1`s and output the length of the longest string of `0`s.

```
    α               Predefined uppercase alphabet
   ⭆                Map over characters and join
       θ            Log array input
      ⬤             All satisfy
           λ        Current log
          Ｅ         Map over elements
             ι      Outer character
            ‹       Less than
              ν     Inner character
         Σ          Summed
        ⊖           Decremented
   ⪪           1    Split on literal `1`
  ⌈                 Take the maximum (longest)
 Ｌ                  Take the length
Ｉ                   Cast to string
                    Implicitly print

```
> 2 votes

# Answer
# Haskell, ~~77~~ 66 bytes

```
f l=maximum$scanl(\m c->sum[m+1|any(foldr1(/=).map(c>))l])0['A'..]

```

Try it online!

-11 bytes thanks to @xnor by reformulating as a `scanl` and informing me that `['A'..]` is a finite list!

`f` computes for each character in effectively `A..Z` whether or not it is starting point of a traversable leg, and keeps track of the running count.

The magic is in the condition `any(foldl1(/=).map(c>))l` which makes use of the fact that `x` is comprised of length 2 strings. `map(c>)` asks whether each endpoint of the journey is beyond `c` and `foldl1(/=)` takes the `xor` of the results, so `c` satisfies this condition only when it is in the half-inclusive journey. If `c` satisfies this for any journey, our count will get incremented, otherwise reset to `0`.
> 2 votes

# Answer
# Jelly, 14 bytes

```
ØA<þ^/€€|/ṣ0ṀL

```

Try it online!

This steals the idea to check if a letter precedes neither or both bound to determine if it's in range from Neil's Charcoal answer. Go upvote them!

## Explanation

```
ØA<þ^/€€|/ṣ0ṀL  Main Link; takes a list of pairs of characters
   þ            Make a product table
  <             using the < operator
ØA              between the entire uppercase alphabet
                and the input (gives a list of lists of pairs)
       €        For each sublist (corresponding to a input pair)
      €         For each pair (corresponding to each letter in the alphabet)
    ^/          Reduce by logical XOR (now a list of length-26 lists each being 0 or 1 depending on if the letter is in the range)
        |/      Reduce the entire thing by logical OR (now a length-26 list with 1 where the letter is in a range and 0 otherwise)
          ṣ0    Split at 0s
            Ṁ   Maximum
             L  Length

```
> 1 votes

# Answer
# JavaScript (V8), 177 bytes

```
b=>Math.max(...b.map(t=>[...t].sort()).sort((w,x)=>(w[0]>x[0])-.5).reduce((r,x)=>x[0]<p[1]?(p[1]=(x[1]<p[1]?p:x)[1],r):[p=x,...r],p=[]).map(g=>(i=parseInt)(g[1],36)-i(g[0],36)))

```

Try it online!

Tried to do this without looking at any of the other answers' tricks. This can potentially be pretty heavily outgolfed.
> 0 votes

---
Tags: code-golf, tree-traversal
---


title: Guide my eyes in the right direction

text:
# Question
Title: Guide my eyes in the right direction
Inspired by this: http://nolandc.com/smalljs/mouse\_reveal/ (source).

A valid answer:

* Takes a number \\$w\\$ and (assumed non-negative) integer \\$x\\$.
* Starts with an integer list with a length of \\$2^w\\$, initially filled with zeroes.
* For each number \\$n\\$ from \\$0\\$ to \\$w-1\\$ (inclusive), divides the list into sub-lists of size \\$2^n\\$, then increments all of the values in the sub-list that contains the index \\$x\\$.
* Returns this list

(Of course a program doesn't have to do exactly this if it returns the right results. If someone finds a good declarative algorithm I will upvote it.)

## Examples

(examples are 0 indexed, your answer doesn't have to be)

```
w=3, x=1
23110000

w=2, x=2
0021

w=3, x=5
00002311

w=4, x=4
1111432200000000

w=2, x=100
Do not need to handle (can do anything) because x is out of bounds

```

### Example of basic algorithm for \\$w=3, x=5\\$

* List is \\$\[0,0,0,0,0,0,0,0\]\\$
* \\$n\\$ is \\$0\\$, list is split into \\$\[\[0\],\[0\],\[0\],\[0\],\[0\],\[0\],\[0\],\[0\]\]\\$, \\$x\\$ is in sixth sub-list, list becomes \\$\[0,0,0,0,0,1,0,0\]\\$
* \\$n\\$ is \\$1\\$, list is split into \\$\[\[0,0\],\[0,0\],\[0,1\],\[0,0\]\]\\$, \\$x\\$ is in third sub-list, list becomes \\$\[0,0,0,0,1,2,0,0\]\\$
* \\$n\\$ is \\$2\\$, array is split into \\$\[\[0,0,0,0\],\[1,2,0,0\]\]\\$, \\$x\\$ is in second half, array becomes \\$\[0,0,0,0,2,3,1,1\]\\$
* Result is \\$\[0,0,0,0,2,3,1,1\]\\$

# Answer
# Jelly, 10 bytes

```
2*Ḷ^‘l2Ċ⁸_

```

A dyadic Link that accepts \\$w\\$ on the left and \\$x\\$ on the right and yields a list of integers.

**Try it online!**

### How?

```
2*Ḷ^‘l2Ċ⁸_ - Link: integer, w; integer x   e.g.  3; 5
2          - two                                 2
 *         - (2) exponentiate (w)                8
  Ḷ        - lowered range                       [0,1,2,3,4,5,6,7]
   ^       - XOR (x)                             [5,4,7,6,1,0,3,2]
    ‘      - increment                           [6,5,8,7,2,1,4,3]
     l2    - log base two                        [2.58,2.32,3,2.80,1,0,2,1.58]
       Ċ   - ceiling                             [3,3,3,3,1,0,2,2]
        ⁸  - chain's left = w                    3
         _ - subtract                            [0,0,0,0,2,3,1,1]

```

---

Without floating points involved, also 10: `2*Ḷ^ḤBẈ⁸_‘`
...would be 8 if `0` in binary were `[]` rather than `[0]` (`2*Ḷ^BẈ⁸_`)
> 9 votes

# Answer
# 05AB1E, 10 bytes

```
ox<Ÿ^bεÀ1k

```

Try it online! or Try all cases!

The idea is to count for each index how many leading bits are the same as \\$x\\$'s bits.

`ox<Ÿ` push integers between \\$2^w\\$ and \\$2^{w+1}-1\\$.
`^` xor every integer in the range with \\$x\\$.
`b` convert each number to binary.
`ε` for each binary string:
`À` rotate the leading \\$1\\$ to the back.
`1k` find the index of the first \\$1\\$. This is first bit that differs between the current index and \\$x\\$.
> 8 votes

# Answer
# , 29 28 27 bytes

```
+/@(<./\)@({=|:@])2#:@i.@^]

```

Try it online!

Consider `1 f 3`:

* `[:#:@i.2^]` Numbers 0 through `2^n-1` in binary:

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

```
* `{` From those, the item at index 1:

```
0 0 1

```
* `=|:@]` Check elementwise equality between that and every number from step 1 (note only the element itself is equal everywhere `1 1 1`). We also transpose the result:

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

```
* `<./\` Column-wise cumulative minimum:

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

```
* `+/` Column-wise sum:

```
2 3 1 1 0 0 0 0

```
> 6 votes

# Answer
# MATL, 22 bytes

```
W:~Ti(1Gq:W"t@etaY|1e+

```

Inputs *w*, then *x*, where *x* is 1-based.

Try it online! Or verify all test cases.

### Explanation

```
W       % Input (implicit): w. Exponential with base 2. Gives 2^w
:~      % Range, negate. Gives [0 0 ... 0] (row vector with length 2^w)
T       % Push true (1)
i       % Input: x
(       % Write 1 at position x (1-based). Gives for example [0 1 0 0 0 0 0 0]
1G      % Push w again
q:      % Subtract 1, range. Gives [1 2 ... w-1]
W       % Exponential with base 2, element-wise. Gives [2 4 ...2^(w-1)]
"       % For each k in [2 4 ...2^(w-1)]
  t     %   Duplicate the current row vector; initially [0 1 0 0 0 0 0 0]
  @e    %   Reshape with k rows, in column-major order. For example, for k=2 this
        %   gives [0 0 0 0;
        %          1 0 0 0]
  ta    %   Duplicate, any. For each column, gives true if there is some nonzero
        %   In the example this gives [1 0 0 0]
  Y|    %   Logical "or", element-wise with broadcast. In the example this gives
        %   [1 0 0 0;
        %    1 0 0 0]
  1e    %   Reshape with 1 row. In the example this gives [1 1 0 0 0 0 0 0]
  +     %   Add, element-wise. In the example this gives [1 2 0 0 0 0 0 0]
        % End (implicit)
        % Display (implicit)

```
> 5 votes

# Answer
# Haskell, 59 bytes

```
0#x=[0]
w#x|(a,b:c)<-splitAt x$(w-1)#div x 2<*".."=a++b+1:c

```

Try it online!

## How?

Recursive implementation, starting from the base case `0#x=[0]`. To compute `w#x`, perform the following steps (exemplified with `w=3`, `x=1`).

```
Compute (w-1)#div x 2                   -- 2#0 = [2,1,0,0]
Duplicate every number                  -- [2,2,1,1,0,0,0,0]
Add +1 to the number at position x      -- [2,3,1,1,0,0,0,0]

```
> 5 votes

# Answer
# K (ngn/k), ~~22~~ 18 bytes

-4 bytes thank sto coltim!

```
{+/&\t=(+t:!x#2)y}

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), 60 bytes

Expects `(w)(x)`. Returns a string.

```
w=>g=(x,i)=>i>>w?'':(h=k=>k--&&!((i^x)>>k)+h(k))(w)+g(x,-~i)

```

Try it online!
> 3 votes

# Answer
# Java, ~~88~~ ~~85~~ 84 bytes

```
x->w->{int a,r[]=new int[w=1<<w];for(;w>1;)for(a=w/=2;a-->0;++r[a+x/w*w]);return r;}

```

*Saved 1 byte thanks to Olivier Grégoire.*

Try it online!
> 3 votes

# Answer
# , ~~50~~ 46 bytes

```
function(w,n)w+-log2(bitwXor(1:2^w-1,n)+1)%/%1

```

Try it online!

A function taking `w` and `n` as arguments and returning a vector of integers. Saved 18 bytes by changing tack to an R version of @JonathanAllan’s clever Jelly solution.

Thanks to @pajonk for saving 4 bytes!

---

# Original version: , 68 bytes

```
function(w,n)colSums(matrix(1:2^w-1,w,2^w,T)%/%(y=2^(1:w-1))==n%/%y)

```

Try it online!
> 3 votes

# Answer
# Haskell, 59 bytes

```
w%x=[sum[1|k<-[0..w-1],i`div`2^k==x`div`2^k]|i<-[0..2^w-1]]

```

Try it online!

For each `i` in `[0..2^w-1]` we count all the `k ∈ [0..w-1]` such that \\$ \big\lfloor \frac{\mathtt i}{2^\mathtt k} \big\rfloor = \big\lfloor \frac{\mathtt x}{2^\mathtt k} \big\rfloor \\$.
> 3 votes

# Answer
# Python 3, ~~57~~ 54 bytes

The same approach as my other answer.

-3 bytes thanks to att!

```
lambda w,x:[w+3-len(bin(2*(n^x)))for n in range(2**w)]

```

Try it online!
> 2 votes

# Answer
# Jelly, 26 bytes

```
Ṭo2*0ẋƲ}WŒH€Ẏ$⁹Ð¡ḊSṁ$€€F€S

```

Try it online!

This is probably entirely the wrong approach.

```
Ṭo2*0ẋƲ}WŒH€Ẏ$⁹Ð¡ḊSṁ$€€F€S  Main Link; take `x` on the left and `w` on the right; `x` is one-indexed
Ṭ                           An array with a 1 in index `x`
 o                          Logical OR with (to get the array to the right size)
  ----Ʋ}                    (Four links applied to the right argument)
  2*0ẋ                      [0] * (2 ^ w)
        W                   Wrap this into a list; [[0, ..., 1, ..., 0]]
              ⁹Ð¡           Repeat w times, collecting intermediate results
         [.]-$              (Apply these two links)
         ŒH€                Split each sublist into two halves
            Ẏ               Tighten; dump these halves into the list itself
                 Ḋ          Remove the first sublist (we could also decrement the final sum)
                      €     For each stage / collected intermediate
                  --$€      For each sublist, apply two links
                  S         Sum of the list (could be maximum too)
                   ṁ        Molded to the shape of the list
                       F€   Flatten each
                         S  and sum the result

```
> 1 votes

# Answer
# Jelly, 15 bytes

```
2*rḤ$Ṗ^Bṙ€1i€1’

```

Try it online!

Port of ovs' 05AB1E answer

## How it works

```
2*rḤ$Ṗ^Bṙ€1i€1’ - Main link. Takes W on the left and X on the right
2*              - 2 ** W
    $           - Last 2 links as a monad f(2 ** W):
   Ḥ            -   2 ** (W+1)
  r             -   Inclusive range
     Ṗ          - Right-exclusive range
      ^         - XOR with X
       B        - Convert to binary
        ṙ€1     - Rotate each one step to the left
           i€1  - First index of 1 in each
              ’ - Decrement

```
> 1 votes

# Answer
# C++, 86 bytes

```
[](int w,int x){int*r=new int[w=1<<w],a;for(;a=w/=2;)for(;a--;++r[a+x/w*w]);return r;}

```

Try it online!
> 1 votes

# Answer
# Jelly, 14 bytes

```
Ż2*ṪḶ:ⱮƊ=":@ɗS

```

Try it online!

A dyadic link taking `w` as the left argument and `x` as the right. Returns a list of integers

## Explanation

```
Ż              | 0..w
 2*            | 2 to the power of each of these
            ɗ  | Following as a dyad:
       Ɗ       | - Following as a monad
   Ṫ           |   - Tail
    Ḷ          |   - Range from 0 to this
     :Ɱ        |   - Integer divide by the remaining powers of two
        ="     | - Equal to:
          :@   |   - n integer divided by the same powers of two
             S | Sun

```
> 1 votes

# Answer
# Charcoal, 22 bytes

```
ＮθＮη⭆Ｘ²θΣＥθ⁼÷ηＸ²λ÷ιＸ²λ

```

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

```
Ｎθ                      First input as a number
  Ｎη                    Second input as a number
      ²                 Literal `2`
     Ｘ                  Raised to power
       θ                First input
    ⭆                   Map over implicit range and join
          θ             First input
         Ｅ              Map over implicit range
                  ι     Outer index
                 ÷      Integer divided by
                    ²   Literal 2
                   Ｘ    Raised to power
                     λ  Inner index
           ⁼            Equals
             η          Second input
            ÷           Integer divided by
               ²        Literal 2
              Ｘ         Raised to power
                λ       Inner index
        Σ               Take the sum
                        Implicitly print

```

Outputs a string, so only works for `w<10`. Add 1 byte to output a list.
> 1 votes

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

```
w=>g=(x,i)=>i>>w?'':(l=v=>v?l(v>>1)-1:w)(i^x)+g(x,-~i)

```

Try it online!

---

# JavaScript (Node.js), 55 bytes

```
x=>g=(w,n=0,h=_=>g(w,n+!(x>>w)))=>w--?h()+h():(x--,[n])

```

Try it online!
> 1 votes

# Answer
# Stax, 13 bytes

```
Ç┌┼σc┤0Θ▬-◙♂A

```

Run and debug it
> 1 votes

# Answer
# Julia 1.0, 48 bytes

```
w$x=[w+1-ndigits(2(n⊻x),base=2) for n=0:2^w-1]

```

Try it online!

Port of ovs's answer
> 1 votes

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


title: Rotation-safe quine

text:
# Question
Title: Rotation-safe quine
Write a proper quine whose every rotation is itself a proper quine.

For example, if your source code is `abcdef`, then:

* `abcdef` would output `abcdef`
* `bcdefa` would output `bcdefa`
* `cdefab` would output `cdefab`
* `defabc` would output `defabc`
* `efabcd` would output `efabcd`
* `fabcde` would output `fabcde`

A rotation "is made by splitting a string into two pieces and reversing their order".

## Scoring

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Answer
> 26 votes
# Alice, ~~138~~ ~~128~~ ~~74~~ 70 bytes

```
<pp&a0Ra*880R9Z640R8Z5e0R7*a70R6Z060R5Z9e0R4Z4R20R3*79Y3Zea0eZ1R51!Z73

```

Unfortunately, I had to fix a bug in the interpreter to make this work, so the current version doesn't work on TIO. But you can try the 128-byte solution online.

You can use this Python script to verify that it works for all rotations, but again you'll have to run it locally against an up-to-date interpreter for the latest version. (Thanks to Jo King for providing that.)

## Explanation (for 74-byte solution)

(Link to an explanation of the original 138-byte solution.)

I was trying find a 2D language for Razetime's bounty where this might be possible and it turned out that it's actually very feasible in Alice. Unfortunately, the solution is a one-liner, not making much use of the two dimensions. That said, I'd be *very* impressed if this is possible with an actual 2D program (in any language), because almost every rotation would have one line broken into two pieces (one at the start and one at the end). I imagine a language would have to have a) multiple explicit entry points and b) a way to determine where on the grid an instruction pointer is to pick one that starts in a "safe" region of the grid. And then you'd still have to implement a quine for this that can work out what the actual current rotation is. So... uhhh...

### Printing the quine

Anyway, let's talk about this solution. I'm using grid manipulation (or self-modifying) command `p` to write our *actual* program into the grid. The main trick for letting me get below 100 bytes is to write that code *outside* the initial grid, specifically to the left of it (at negative **x** indices). This self-modification works regardless of the applied rotation (we'll get into why later), and prepends the following snippet to the code:

```
@o&J'h%p't"

```

This code will be executed from right to left. By the time we get here:

* there might be some rubbish left on the stack (depending on the rotation) - in one case, there might be an iterator in the queue (more about that later)
* in two cases (specifically those starting with a `p`) the first character of the original source code has been replaced with a null
* otherwise the original source always remains unchanged.

Before we get into how and why this self-modification works consistently, let's look at what the new code does.

```
"   Toggle string mode. While in string mode, Alice records every
    codepoint the IP travels over (with some caveats that don't
    matter). Since there's only one " on the grid, we'll record
    every other cell, wrap around, and eventually hit " again.
    When we leave string mode again, all of the codepoints get
    pushed to the stack.
    There'll be a bunch of useless stuff at the bottom of the stack
    now but what's important is that the top 74 values are the
    original source code in reverse order.
    However, the leading 'p' might have been replaced with a null.
    Let's fix that.
t   Decrement.
'p% Modulo 112. Since 'p' is the biggest codepoint in the original
    source, this won't affect any value that corresponds to an
    actual character. But if we had a 0, -1 % 112 becomes 111.
h   Increment. We've now mapped 0 to 112 and left all values from 1
    to 112 unchanged.
'J  Push 74, which happens to be the length of the source code.
&o  Pop and print that many characters from the top of the stack.
@   Terminate the program.

```

### Generating the printing code

On to the question of how we apply this source modification in the first place. Let's go back to half of the initial code:

```
<pp&ha0Na*880RaZ640R9Z5e0R8Z620R7Z060R6Z9e0R5Z4R20R4Z730R3Z060R2Zea0eZ1R51

```

We start on a `<` which makes the instruction pointer (IP) move west instead of east. The IP wraps around the edges, so we really start executing the code from the end and should once again read this code in reverse.

This makes use of `p`, which pops **y**, **x**, **v** and writes value/codepoint **v** to the location **(x, y)**. We use `ah&` to execute `p` 11 times, though the second `p` will add a 12th invocation. It's important for those to happen only in one place in the code for all rotations to work. All the other stuff before that just prepares the stack with inputs for these twelve invocations of `p`. Breaking the code down into `v, x, y` triples:

```
v     x   y

          1
5R1Z  e   0
aeZ   2R  0
60Z   3R  0
37Z   4R  0
2R4Z  5R  0
e9Z   6R  0
60Z   7R  0
26Z   8R  0
e5Z   9R  0
46Z   aR  0
88*   aN  0

```

Apart from pushing individual digits, there are only a few commands of note here. `e` pushes **-1**. `a` pushes **10**. `R` multiplies the top of the stack by **-1**. `N` computes the bitwise NOT. And then there's `Z`. You'll notice that most of them make use of it, the *zip* command. This command computes a bijection from a pair of integers to a single integer. The intended usage is to encode lists or other collections of numbers in a single number (to make it easier to store on the tape or the grid, for example), but it happens to be very useful for generating larger numbers in few characters. You can use this Alice program to figure out which two numbers you need to get the desired result.

Also note that there's an additional **1** at the bottom of the stack. This is the only relevant input for the 12th invocation of `p`. Since this is the **y** this writes some garbage somewhere on the second line of the program, which we'll never encounter.

### Rotating the source

Finally, let's look at how various rotations of the source code behave. I'm going to shorten our "unrotated" source code to `<pp&haZYX` where `ZYX` represents the code that pushes all the constants. Let's go through the various possibilities:

```
pp&haZYX<

```

Here, we start on a `p`, which immediately reads three implicit zeros from the empty stack and replaces itself with a null. This is the reason any solution will *need* two `p`s, because the rotation which starts with `p` immediately loses it before it can do anything useful. For this particular rotation, we immediately run into another `p`, which does nothing and then `&haZYX` pushes a ton of random numbers we're never going to use. Finally `<` moves us left and we basically move through the exact same code as in the unrotated source, except we don't have the additional `p` any more (but that only wrote a useless character to the second line anyway).

```
p&haZYX<p

```

This one behaves a bit differently. The initial `p` still removes itself, so the behaviour isn't really different until we hit `<` move back and push all the constants. However, now when reach the left end of the code, our *actual* `p` hasn't been executed yet, so the quine-printing code doesn't exist yet. The IP wraps around and we finally modify the source with the `p` at the end. Then the IP moves through `ZYX` again, uselessly pushing the constants again. Finally, we end on `&ha` *just* before the `"`.

String mode works such that it makes use of the iterator queue when *leaving* string mode. So what this does is that we end up pushing all of the grid codepoints to the stack 11 times instead of once. But since we're only working with the top 74 stack values anyway, we don't care about the other 10 copies at all and this rotation ends up working as well.

Next:

```
&haZYX<pp

```

This is basically the same, except we don't replace a `p` with null (but do write a rubbish character to the second line).

And finally, putting the rotation anywhere inside the code that pushes constants:

```
YX<pp&haZ

```

This isn't fundamentally different, we just push a smaller amount of rubbish to the stack before hitting the `<` and executing the proper code.

# Answer
> 17 votes
# Motorola MC14500B Machine Code, 1 byte

The 1 byte score is derived from two 4-bit instructions:

```
0000 0010

```

## Explanation

> The Motorola MC145008 is a single chip, one-bit, static CMOS processor optimized for decision-oriented tasks. The processor is housed in a 16-pin package and features 16 four-bit instructions. The instructions perform logical operations on data appearing on a one-bit bidirectional data line and data in a one-bit accumulating Result Register within the ICU. All operations are performed at the bit level.

The pins of the processor are numbered:

> Instructions are presented to the chip on the 4 instruction pins, (`I0`, `I1`, `I2`, `I3`), and are latched into the Instruction Register, (IR), on the negative-going edge of X1.

In layman's terms, pins 4 through 7, are used to present the Instruction Register with an instruction, but the bits are interpreted in the reverse order. For example, the instruction `0001` would have pin #7 in the high state and pins 6 through 4 in the low state.

> The instructions, are decoded in the Control Logic (CTL), sending the appropriate logic commands to the LU. Further decoding is also performed in the CTL to send a number of output flags (`JMP`, `RTN`, `FLGO`, `FLGF`) to pins 9 through 12. These are used as external control signals and remain active for a full clock period after the negative-going edge of X1.

Or, put simply, pins 9 through 12 are the output flags `FLGF`, `FLGO`, `RTN`, and `JMP`, respectively. Note that data is typically multiplexed to the `WRITE` pin (pin #2). The output flag pins are similar to other language's exit codes.

> Each of the ICU's instructions execute in a single clock period.

## Rotations

### Initial position

```
0000    NOPO
0010    LDC

```

The clock periods:

1. The `NOPO` instruction puts pin #10 (`FLGO`) in the high state. Before the next clock period, the output flag pins are put back into the low state.
2. The `LDC` instruction loads the complement of the Data Bus' value to the Result Register, without affecting the output flag pins.

So, during the program's two clock periods, the output flag pins have represented `0100 0000`, which, read in reverse (like the input pins), is `0000 0010`, or the original instructions.

### First rotation

```
0010    LDC
0000    NOPO

```

The clock periods:

1. The complement of the Data Bus is loaded to the Result Register, with no effect of the output flag pins.
2. Pin #10 in switched to the high state.

During these two clock periods, the output flag pins have represented `0000 0100`, which, when reversed, are the instructions `0010 0000`.

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