# Question
Title: Repeat Hello World according to another string's length
This was related to a program I am writing. Although the title is simple, the challenge is a lot more complicated.

## Your challenge

You must write a program that takes an input, and your answer must match the sample outputs in this question.

What the program should be is that you must output "HelloWorld" with the length of the input matching the length of what you output. If the input's length is not divisible with 10, you should cut off the last few letters until it matches the length of the last few letters of the input. More clarification in the examples.

**Standard loopholes apply, except that answers should be full programs, and the input has to be printable ASCII.**

## Example inputs

```
Input:  how are you
Output: HelloWorldH

Note: In the above example, there is an extra H due to the
characters in the input being 11, so we add an extra letter

Input:  hrienehwnv
Output: HelloWorld

Input:  kill him at dawn
Output: HelloWorldHelloW

```

This is , so shortest answer wins!

---

Steffan won the first +50 bounty reputation award for 5 bytes. I know lyxal also had a 5 bytes with the same language, but previously he had his answer with 8 bytes, before he shortened it to 5 bytes, but after Steffan's answer had already been posted.

# Answer
# Vyxal, 5 bytes

```
LkhȧẎ

```

Try it Online!
> 2 votes

# Answer
# JavaScript, ~~45~~ 35 bytes

```
s=>"".padEnd(s.length,"HelloWorld")

```

Try it online!

−10 thanks to Arnauld.
> 11 votes

# Answer
# sed, ~~111~~ ~~55~~ ~~51~~ 44 bytes

```
s/./a/
:a
s/^/HelloWorld/
s/.\{10\}$//
/a/ba
```

Attempt This Online!
> 8 votes

# Answer
# Haskell, 30 bytes

```
map fst.zip(cycle"HelloWorld")

```

Try it online!

A cute way to truncate one string to the length of another is to `zip` them together, which truncates the longer string, then extract the desired string with `map fst`.

Longer alternatives:

```
fst.unzip.zip(cycle"HelloWorld")
zipWith const$cycle"HelloWorld"

```
> 7 votes

# Answer
# Python, 39 bytes

```
lambda s:('HelloWorld'*len(s))[:len(s)]

```

Attempt This Online!

# Python, 39 bytes

Alternative version proposed by `mazunki`:

```
lambda s:('HelloWorld'*(l:=len(s)))[:l]

```

Attempt This Online!
> 7 votes

# Answer
# Charcoal, 13 bytes

```
…HelloWorldＬＳ

```

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

```
 HelloWorld     Literal string `HelloWorld`
…               Reshaped to length
           Ｌ    Length of
            Ｓ   Input string

```
> 5 votes

# Answer
# 05AB1E, 9 bytes

```
”Ÿ™‚ï”áI∍

```

Input as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
”Ÿ™‚ï”     # Push dictionary string "Hello World"
      á    # Only keep letters to remove the space: "HelloWorld"
       I   # Push the input-list
        ∍  # Shorten/extend the "HelloWorld" string to its length
           # (after which the result is output implicitly)

```

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

# Answer
# Excel, 38 bytes

```
=LEFT(REPT("HelloWorld",3276),LEN(A1))

```

Input is in the cell `A1`. Output is wherever the formula is.

Repeats the string as many times as allowed based on the limitations of inputs to `LEFT()` and the truncates all but the left-most characters based on the length of the input.
> 5 votes

# Answer
# C (gcc), 55 bytes

```
main(c){for(;~getchar();)printf(L"dHelloWorl"+c++%10);}

```

Try it online!
> 5 votes

# Answer
# Pyth, 25 bytes

```
FNrZlwp@"HelloWorld"%N 10

```

Try it online!

PS: first time using Pyth & this platform is awesome!
> 4 votes

# Answer
# Retina, 27 bytes

```
T`p`~
Y`~`\He\l\l\oW\or\l\d

```

Try it online! Explanation:

```
T`p`~

```

Translate all the characters to `~`s.

```
Y`~`\He\l\l\oW\or\l\d

```

Cyclically translate all the `~`s to the characters `HelloWorld`. Note that unfortunately most of them have special meanings to translate so that they have to be quoted.
> 3 votes

# Answer
# Perl 5 \+ `-pl`, 23 bytes

Inspiration taken from @Neil's Retina answer. 3 bytes saved thanks to @Sisyphus!

```
$_&=HelloWorld x y//./c
```

Try it online!

## Explanation

Sets `$_` (which will be implicitly output via `-p`) to the result of stringwise `AND`ing a string of `HelloWorld`s repeated once for the count of each char in the input (implicitly stored in `$_` via the implicit `-n` from `-p`) when `tr///`ansliterated (`y///`) from any char to `\xFF`s. This operation results in a string the length of the original input with the content `HelloWorld` truncated accordingly.
> 3 votes

# Answer
# Vyxal `s`, 5 bytes

```
ẏkhȧİ

```

Try it Online!

Can't believe I had to find a new 5 byter because someone got my answer by 2 bytes shorter :p.

## Explained

```
ẏkhȧİ
ẏ     # The range [0, len(input)]
 khȧ  # The string "HelloWorld"
    İ # The range indexed into the characters of the string.

```

## Vyxal `sr`, 5 bytes

```
khȧf•

```

Try it Online!

More flags and more ways that I won't be outgolfed again. Takes input as a list of characters

### Explained

```
khȧf•
khȧf  # The string "HelloWorld" as a list of chars
    • # Molded to the shape of the input

```
> 3 votes

# Answer
# Knight, 23 bytes

```
O G*"HelloWorld"=cL P0c

```

Try it online!
> 3 votes

# Answer
# brainfuck, 180 bytes

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

```

Try it online!

Can likely be golfed quite a bit more, as the majority of the code is setting up the string "HdlroWolle" on the tape.

Explanation:

```
>+[++[++>]<<+]>+                          108 = 'l'
[->>+>+>+>+>+>+>+>+>+<<<<<<<<<<]          ptr before '\0lllllllll'

-[>+<-------]>-                           ptr on 'H'

>--------                                 'd'
>                                         'l'
>++++++                                   'r'
>+++                                      'o'
>---------------------                    'W'
>+++                                      'o'
>                                         'l'
>                                         'l'
>-------                                  'e'    ("HdlroWolle")

> ,[>+<,]         [Read all input, counting the length of it 2 cells after the string.]

>[-<                                      Do len(input) times:

<[                                        Shift the string right by 1
    [->+<]
    <
]
[see https://www.codingame.com/playgrounds/50443/brainfuck-part-2---working-with-arrays]

[Print the first character of the string and move the far
 right cell back to the beginning, rotating the string.]
>>.>>>>>>>>>[-<<<<<<<<<<+>>>>>>>>>>]

>]                                        End loop

```
> 3 votes

# Answer
# Haskell, 33 bytes

```
($cycle "HelloWorld").take.length

```

Try it online!
> 2 votes

# Answer
# Factor \+ `sequences.repeating`, 33 bytes

```
[ "HelloWorld"swap length cycle ]

```

Try it online!
> 2 votes

# Answer
# lin, 25 bytes

```
"HelloWorld"`cyc.~ len `t

```

Try it here! Returns an iterator.

For testing purposes:

```
"how are you" ; `_` outln
"HelloWorld"`cyc.~ len `t

```

## Explanation

Cycle and take (input length) items.
> 2 votes

# Answer
# Jelly, 8 bytes

```
“ ⁷ỴNt»ṁ

```

A monadic Link that accepts a list of characters and yields a list of characters.

**Try it online!**

### How?

Pretty simple...

```
“ ⁷ỴNt»ṁ - Link: list of characters, S
“ ⁷ỴNt»  - dictionary lookup -> "HelloWorld"
       ṁ - mould like S

```
> 2 votes

# Answer
# vim, 46 bytes

```
$mma<C-R>=col('$')
aHelloWorld<C-V><ESC><ESC>`mlDo<ESC>@"khjllDkdd

```

## Annotated

```
$mm                      # Go to the end of input and mark our position
a                        # Append...
  <C-R>=col('$')         #   The column offset/line length
  aHelloWorld<C-V><ESC>  #   This exact string
<ESC>                    # ...which yields a command that prints "HelloWorld"
                         # once per char in the original input. (All that matters
                         # is that this string is at least as long as the output
                         # needs to be.)

`mlD                     # Delete the string we just appended, copying into register "
o<ESC>@"                 # Run the command, putting a bunch of "HelloWorld"s on next line
khjllD                   # Make the new line the same length as the input
kdd                      # delete the input

```

`<C-R>` is 0x12, `<ESC>` is 0x1b, `<C-V>` is 0x16.

Try it online!
> 2 votes

# Answer
# PowerShell, 37 bytes

```
-join($args|%{'HelloWorld'[$i++%10]})

```

Try it online!
> 2 votes

# Answer
# Rust (full program), 145 bytes

The full program rule doubles the length.

```
fn main(){for l in std::io::stdin().lines(){print!("{}",(0..).zip(l.unwrap().chars()).map(|i|b"HelloWorld"[i.0%10]as char).collect::<String>())}}
```

Attempt This Online!

# Rust (function), 85 bytes

```
|l:&str|(0..).zip(l.chars()).map(|i|b"HelloWorld"[i.0%10]as char).collect::<String>()
```

Attempt This Online!
> 2 votes

# Answer
# Alice, 54 bytes

```
/ H l o o l " \w>?hn$vihn$@?]oK
 " e l W r d !  ^(H' <

```

Try it online!

# Flattened

```
/"HelloWorld"!\w>?hn$vihn$@?]oK
                ^(H' <
/"HelloWorld"!\                  Pushes the hello world string on the tape
               w      ihn$@   K  While where are characters to read on the input
                >?hn$v           If the tape is outside of "HelloWorld"
                ^(H' <           Rewind the tape
                           ?]o   Print one character from the tape and move to the next one

```
> 2 votes

# Answer
# Ruby, ~~37~~, 35 bytes

```
->x{('HelloWorld'*l=x.size)[0...l]}

```

Try it online!

-2 bytes thanks to @Steffan
> 2 votes

# Answer
# Zsh, 26 bytes

```
<<<${(r:$#1::HelloWorld:)}
```

Attempt This Online!
> 2 votes

# Answer
# x86‑64 machine code on Linux, 97 B

## input

* `/dev/stdin` connected to a pipe or terminal in cooked mode
* possibly empty input
* Linux zeros processor registers upon process initialization (with the obvious exception of `rsp`).

## source code

Uses NASM – the Netwide Assembler. Overview of algorithm:

1. Infinitely wait until data become available. (`select`)
2. Query total number of Bytes immediately available for reading. (`FIONREAD`)
3. Discard input. (`TCIFLUSH`)
4. Integer division: Bytes that were available for reading count divided by 10.
5. Loop: Whole 10 Byte writes of `'HelloWorld'`.
6. Write remainder of integer division Bytes.

```
global _start

bits 64
default rel

; These two constants rather serve as documentation:
STDIN_FILENO         equ   0
STDOUT_FILENO        equ   1
; Linux (`syscall`) system call numbers used in this program:
sys_exit             equ   60
sys_ioctl            equ   16
sys_select           equ   23
sys_write            equ   1
; `ioctl(2)` requests used:
FIONREAD             equ   0x0000541B
TCFLSH               equ   0x0000540B
; Argument to `TCFLSH` request:
TCIFLUSH             equ   0

; ==============================================================
section .text
hello_world:
    db 'Hello'
    db 'World'
; 'HelloWorld'’s length is `10`, but this is cleaner style:
hello_world_length   equ   $ - hello_world

_start:
    ; rax    rdi  rsi    rdx   r10   r8
    ; select(  1, [rsp], NULL, NULL, NULL)
    push 1                      ; bitfield with LSB set
    mov rsi, rsp                ; *readfds
    pop rdi                     ; nfds
    push rdi                    ; rsp for get_iteration_count
    mov al, sys_select
    syscall

get_input_length:
    ; rax   rdi           rsi       rdx
    ; ioctl(STDIN_FILENO, FIONREAD, [rsp])

    xor edi, edi                ; fd := 0 (STDIN_FILENO)
    xchg rsi, rdx               ; bytes available buffer
    mov si, FIONREAD            ; ioctl(2) request number
    mov al, sys_ioctl
    syscall

discard_input:
    ; rax   rdi           rsi     rdx
    ; ioctl(STDIN_FILENO, TCFLSH, TCIFLUSH)

    mov edx, edi                ; TCIFLUSH = 0 → copy zero
    mov sil, TCFLSH & 0xFF      ; TCFLSH − 0x10 = FIONREAD
    mov al, sys_ioctl
    syscall
    ; `rax` may be non-zero now, in particular −ENOTTY.
    test eax, eax               ; for dumb last char = "\n" test
    setns dil                   ; subtrahend = 0 for ENOTTY

get_iteration_count:
    ; Retrieve number of Bytes that were available for reading.
    pop rax
    sub eax, edi                ; subtract 1 if this is terminal
    jc exit                     ; user typed ^D (detach input)

    ; Load divisor.
    push hello_world_length
    pop rcx
    ; eax := number of whole writes; edx := Bytes in partial write
    div ecx

    ; Save Bytes in partial write for `finish_write` below.
    ; The `push rdx`/`pop rdx` pattern is just two 2 Bytes.
    push rdx

    ; Use `ebx` as loop counter, because `syscall` clobbers `rcx`
    ; and this does not require a REX prefix like r8 – r15 do.
    xchg eax, ebx
write:
    ; rax   rdi            rsi          rdx
    ; write(STDOUT_FILENO, hello_world, 10)
    xchg edx, ecx
    lea rsi, [hello_world]
    mov dil, STDOUT_FILENO

    test ebx, ebx               ; zero _whole_ writes test
    jz finish_write             ; zero entire 10B writes
keep_writing:
    mov al, sys_write
    syscall
    dec ebx
    jnz keep_writing

    ; Write the remainining ≤ 9 Bytes.
finish_write:
    pop rdx
    mov al, sys_write
    syscall

exit:
    xchg ebx, edi               ; rdi := 0 (= “successful”)
    push sys_exit               ; need to wipe entire register
    pop rax                     ; because we may have jumped
    syscall                     ; here from get_iteration_count

; vim: ft=nasm:

```

## disassembly

```
helloWorld.o:     file format ELF64-x86-64

Disassembly of section .text:

0000000000000000 <hello_world>:
   0:   48                      rex.W
   1:   65 6C                   gs ins byte ptr es:[rdi], dx
   3:   6C                      ins    byte ptr es:[rdi], dx
   4:   6F                      outs   dx, dword ptr ds:[rsi]
   5:   57                      push   rdi
   6:   6F                      outs   dx, dword ptr ds:[rsi]
   7:   72 6C                   jb     75 <exit + 0x1B>
   9:   64                      fs

000000000000000A <_start>:
   A:   6A 01                   push   0x1
   C:   48 89 E6                mov    rsi, rsp
   F:   5F                      pop    rdi
  10:   57                      push   rdi
  11:   B0 17                   mov    al, 0x17
  13:   0F 05                   syscall

0000000000000015 <get_input_length>:
  15:   31 FF                   xor    edi, edi
  17:   48 87 F2                xchg   rdx, rsi
  1A:   66 BE 1B 54             mov    si, 0x541B
  1E:   B0 10                   mov    al, 0x10
  20:   0F 05                   syscall

0000000000000022 <discard_input>:
  22:   89 FA                   mov    edx, edi
  24:   40 B6 0B                mov    sil, 0xB
  27:   B0 10                   mov    al, 0x10
  29:   0F 05                   syscall
  2B:   85 C0                   test   eax, eax
  2D:   40 0F 99 C7             setns  dil

0000000000000031 <get_iteration_count>:
  31:   58                      pop    rax
  32:   29 F8                   sub    eax, edi
  34:   72 24                   jb     5A <exit>
  36:   6A 0A                   push   0xA
  38:   59                      pop    rcx
  39:   F7 F1                   div    ecx
  3B:   52                      push   rdx
  3C:   93                      xchg   ebx, eax

000000000000003D <write>:
  3D:   87 D1                   xchg   ecx, edx
  3F:   48 8D 35 BA FF FF FF    lea    rsi, [rip + 0XFFFFFFFFFFFFFFBA]
  46:   40 B7 01                mov    dil, 0x1
  49:   85 DB                   test   ebx, ebx
  4B:   74 08                   je     55 <finish_write>

000000000000004D <keep_writing>:
  4D:   B0 01                   mov    al, 0x1
  4F:   0F 05                   syscall
  51:   FF CB                   dec    ebx
  53:   75 F8                   jne    4D <keep_writing>

0000000000000055 <finish_write>:
  55:   5A                      pop    rdx
  56:   B0 01                   mov    al, 0x1
  58:   0F 05                   syscall

000000000000005A <exit>:
  5A:   87 DF                   xchg   edi, ebx
  5C:   6A 3C                   push   0x3C
  5E:   58                      pop    rax
  5F:   0F 05                   syscall

```

Having the `'HelloWorld'` string in the `.text` section is weird, but putting (read-only) data into an already/definitely existing section, i. e. `.text`, makes the executable file smaller. The stripped ELF64 executable file has a size of merely 440 B, not that *that* really mattered for *code* golfing.

## output

* output lacks of a trailing newline
* `HelloWorld` repeating until the input’s length is reached
* on a terminal *input length − 1* accounting for a presumed terminating `"\n"` \[even if the user actually detached from input `Ctrl‑D`\]

## limitations

* I am *not sure*, but *maybe* the `FIONREAD` `ioctl(2)` I am utilizing is capped at `0x7FFFF000` because *one* `read(2)` can transfer at most this many Bytes? Therefore this program’s output will be limited to 2,147,479,552 Bytes accordingly.
* At any rate, there’s a 32-bit `div ecx`, so a string length ≥ 232 is not handled correctly.
* If we’re reading from a pipe, the pipe’s capacity may be the limiting factor. In `pipe(7)`, § pipe capacity, it says the default value is 65536 B (so it can be changed). Similarly, a terminal’s input buffer may have comparable “low” dimensions. Yet these are implementation details *outside* of this program.
> 2 votes

# Answer
# simply, ~~111~~ 106 bytes

This is (yet another) language I'm just working on, for fun.

It is a very verbose language, and still in progress, which is why the algorithm is ... less conventional and very convoluted...

```
def&f($v){$C=&str_chunk("HelloWorld"&len($v));send$C[0];}echo&join(&array_map(&str_chunk($argv[0]10)&f)'')

```

Due to oversights in the parser, the values don't have to have to be separated by commas.

---

## Ungolfed:

```
Create a function called &handle_chunk with arguments ($value).
Begin
    Assign $len the value of executing the function &len with argument $value.

    Set the variable $chunks with the value of calling the function &str_chunk with the arguments "HelloWorld", $len.

    Return the value $chunks[0].
End.

Display the result of calling &join(
    Call the function &array_map with the arguments (
        Run &str_chunk($argv[0], 10),
        &handle_chunk
    ),
    ""
).

```

Should be self-explanatory.

---

## How to run:

Download the repository and open `índex.html`.

---

---

## Unintended method:

This is simply a re-implementation of m90's answer:

```
%c="";def&f($s)call%c->padEnd(&len($s)"HelloWorld");

```

Works the same way as the intended way.
> 1 votes

# Answer
# BQN, 15 bytes

```
"HelloWorld"⥊˜≢

```

Try it at BQN REPL

```
"HelloWorld"⥊˜≢
               ≢    # get the shape (length) of the input
            ⥊˜      # and use this to reshape
"HelloWorld"        # the string "HelloWorld"
                    # (recycling elements if required)

```
> 1 votes

# Answer
## Kustom, 39 bytes

Basically just this Javascript answer.

The extra byte is for the global variable name.

```
$tc(rpad,"",tc(len,gv(i)),HelloWorld)$

```
> 1 votes

# Answer
# PowerShell Core, 35 bytes

```
% L*h|%{'HelloWorld'*$_|% S*g 0,$_}

```

Try it online!

# Windows PowerShell, 38 bytes

```
% L*h|%{'HelloWorld'*$_|% S*g -a 0,$_}

```

Same as above, but PS 5.1 requires actually naming the parameter "-ArgumentList" (shortened to "-a") for the Substring() method call.

Input comes from the pipeline.

Nothing fancy; this is basically
`ForEach-Object {$l = $_.Length; ('HelloWorld' * $l).Substring(0, $l)}`
The expensive method calls can be golfed by using the cmdlet ForEach-Object (that is, its alias "%"), and its possibility to call a method of the input object by name, accepting wildcards.

```
% L*h|%{'HelloWorld'*$_|% S*g 0,$_}
% L*h                                  # "ForEach-Object -MemberName Length": invoke the method "Length" for the string passed in the pipeline
     |                                 # Pipe the length of the input string to the next cmdlet
      %{                               # "ForEach-Object -ScriptBlock {"
        'HelloWorld'*$_                #     repeat the string 'HelloWorld' <Length> times
                       |               #     and pipe the 'HelloWorldHelloWorld...' to the next cmdlet
                        % S*g 0,$_     #     "ForEach-Object -MemberName Substring -ArgumentList 0, <Length>": invoke the method "Substring" for the string passed in the pipeline, get <Length> chars starting at 0
       }                               # }: end of the scriptblock; Output is implicit

```
> 1 votes

# Answer
# PHP (function), 179 bytes

***Used own logic and avoid system define function***

```
function fnc($rs,$as){$dr="";$fv=explode(".",strval(strlen($as)/strlen($rs)));while((int)$fv[0]>0){$dr.=$rs;(int)$fv[0]--;}return $dr.=substr($rs,0,(int)strlen($as)%strlen($rs));}

```

Try it online!

# PHP, 90 bytes

***Sugested by @Steffan***

```
function fnc($a){for($f=strlen($a);$f--;)$d.="HelloWorld";return substr($d,0,strlen($a));}

```

Try it online!
> 1 votes

# Answer
# R (function), 41 bytes

```
`substr<-`(a,1,90,strrep("HelloWorld",9))

```

I assume this can be improved...

This takes advantage of a feature of `substr()` I learned when I was today years old: `substr()` has a replacement function, and if the string replacing the substring is longer than the substring, it is cut off at the appropriate place, which works perfectly for this challenge. We can replace the entire input string `a` with a string of concatenated `"HelloWorld"`s with the last one truncated. This will not work for any string longer than 90 characters but no test cases in the input are that long. To make it work for longer strings, you can replace both of the `90` and `9` with `nchar(a)`.

Try it online!
> 1 votes

# Answer
# , 15 bytes

```
'HelloWorld'$~#

```

Try it online!

Very straightforward.

## Explanation

```
'HelloWorld'$~#
            $~     reshape
'HelloWorld'       this string
              #    by the length of the input

```
> 1 votes

# Answer
# C# (function), 38 bytes

```
x=>x.Select((_,i)=>"HelloWorld"[i%10])

```

Try it online!

---

# C# (full program), ~~102~~ 96 bytes

-6 bytes thanks to TKirishima

```
using System.Linq;System.Console.WriteLine(args[0].Select((_,i)=>"HelloWorld"[i%10]).ToArray());

```

This is a complete program in C#10 thanks to implicit top-level statements. TIO doesn't support this, but .NET Fiddle does.
> 1 votes

# Answer
# Regex (Boost), 76 bytes

```
s/(.(.(.(.(.(.(.(.(.(.)?)?)?)?)?)?)?)?)?)?/?1H?2e?3l?4l?5o?6W?7o?8r?9l?10d/g

```

Try it online!

This is a single regex substitution, to be applied once.

It uses nested conditional replacement. The number of capture groups that get set is the number of characters matched, and they will always be consecutively numbered starting at 1.

It will start by matching the full 10 character length as many times as possible, which will be replaced each time with the full `HelloWorld` string. Then when it reaches a point where there are fewer than 10 characters remaining, it will do its last replacement.

# Regex (PCRE2), 116

`s/(.(.(.(.(.(.(.(.(.(.)?)?)?)?)?)?)?)?)?)?/${1:+H${2:+e${3:+l${4:+l${5:+o${6:+W${7:+o${8:+r${9:+l${10:+d}}}}}}}}}}/g`

Try it on regex101!
Try it online!

PCRE2's conditional replacement syntax is quite a bit more verbose. But you can run this on regex101 and see it work in real time as you type (make sure to erase the test cases first, so it's as fast as possible).
> 1 votes

# Answer
****Swift**, 137 bytes**

```
 var a = readLine()!,h = "HelloWorld",c = h.count,j = a.count,i = Int(j/c),s="";for _ in 0..<i {s += h};s += String(Array(h)[0..<j - i*c])

```
> 1 votes

# Answer
# jq `-R`, 30 bytes

```
("HelloWorld"*length)[:length]

```

Try it online!
> 1 votes

# Answer
# Pushy, 19 bytes

```
LF`dlroWolleH`^:N'}

```

Try it online!
> 1 votes

# Answer
# Gaia, 17 bytes

```
l:“HelloWorld”×¤<

```

Try it online!

Pretty standard approach I think. It's a shame Gaia does not have a reshape to length built-in like BQN/J :(

## Explained

```
l:“HelloWorld”×¤<
l                  # Length of the input
 :                 # push a second copy of that
  “HelloWorld”     # push the string "HelloWorld" to the stack
              ×    # repeat that string by the length of the input
               ¤<  # push the second copy of the length to the top of the stack and get the first n characters of the string

```
> 1 votes

# Answer
# Japt, 9 bytes

```
î`HÁMWld

```

Try it

```
î`HÁMWld     :Implicit input of string
î             :Repeat & slice the following to length of input
 `HÁMWld     :  Compressed string "HelloWorld"

```
> 1 votes

# Answer
# Julia 1.0, 37 bytes

```
~=length;!a=("HelloWorld"^(~a))[1:~a]

```

Try it online!
> 1 votes

# Answer
# Vim, 28 bytes

```
D@=le<Tab>@")
iHelloWorld<Esc>@=
|lD

```

Try it online!

### Explanation

```
D                   # Delete the input into the @" register
 @=                 # Set @= register to:
   le<Tab>  )       #   The length of:
          @"        #     The @" register
iHelloWorld<Esc>    # Type "HelloWorld" @= times
                @=  #
|                   # Move cursor to position @=
 lD                 # Delete everything after the cursor

```
> 1 votes

# Answer
# \*\>\<\>, 41 bytes

Uses the `-i` flag to initialize the stack with our input value.

```
l1["dlroWolleH"    v
or1-:?!;rl2(?!u20.O>

```

Try it online!

## Explanation

```
l                    Push the length of the stack onto the stack
 1[                  Pop that length value into a new stack
    "dlrowolleh"     Push "HelloWorld" reversed onto the stack
                   v Change IP Direction downward

                   > Change IP direction rightward
o                    Pop a value off the stack, print it as a char
 r                   Reverse the stack, putting the length value on the top of the stack
  1-:                Subtract one from that value
     ?!;             If that value is 0, halt execution
        r            Reverse the stack
         l           Check the length of the stack
          2(         Is it less than two (Do we have more to print, but have run out of our HelloWorld string)
            ?!u      If NOT, ignore instructions until the next O
               20.   If so, jump to [0,2] in the code box, just before pushing HelloWorld onto the stack
                  O  Else, continue onto the >

```
> 0 votes

# Answer
# C (clang), 47 bytes

```
i;f(*s){for(i=0;*s;*s++="HelloWorld"[i++%10]);}

```

Try it online!
> 0 votes

# Answer
# \>\<\>, 19 bytes

```
"HelloWorld"i0(?;{o

```

Try it online!

**Explanation**

```
"HelloWorld"         # push the string "HelloWorld"
            i0(?;    # take input, if there isn't more input, exit program
                 {o  # else print the bottom of the stack

```
> 0 votes

# Answer
# JavaScript, 35 bytes

I/O as an array of characters.

```
s=>s.map((_,x)=>"HelloWorld"[x%10])

```

Try it online!
> 0 votes

# Answer
# Thunno 2, 6 bytes

```
khỊsØE

```

Try it online!

#### Explanation

```
khỊsØE  # Implicit input
khỊ     # Push "HelloWorld"
   sØE  # Extend/truncate it
        # to the input's length
        # Implicit output

```
> 0 votes

# Answer
# Lua, 43 bytes

```
print(("HelloWorld"):rep(#...):sub(1,#...))

```

Try it online!
> 0 votes

---
Tags: code-golf, string, hello-world
---


title: Cell`s Life #1: Simulate a plant cell

text:
# Question
Title: Cell`s Life #1: Simulate a plant cell
# What am I?

As a plant cell, your program/function/etc. must undergo photosynthesis:
When the input is `6CO2+6H2O+light` in any order, output `C6H12O6+6O2` in any order. It does not have to be the same for each arrangement of the input.
When the input is just `r`, replicate (i.e. output your own code). rules apply.
When input is anything else, output the input (i.e. cat program) (so your cell doesn't expend energy by trying to process useless chemicals)

# Rules without the cell's whole life story

When the input is any of the following:

```
6CO2+6H2O+light
6CO2+light+6H2O
6H2O+6CO2+light
6H2O+light+6CO2
light+6CO2+6H2O
light+6H2O+6CO2

```

Output either `C6H12O6+6O2` or `6O2+C6H12O6`. You do not have to output the same one for each of the 6 inputs.

When the input is just `r`, be a quine (output the source code).

When the input is anything else (or empty), be a cat program (output the input).

Your answer/submission may be a full program, or a function, etc.

Standard loopholes apply (as always); especially this.

## Python, *ungolfed noncompeting example*

Noncompeting as it breaks quine rules.

```
inp = input()
s = input.split('+') # List of chemicals
a = '6CO2' in s  # Has CO2
b = '6H2O' in s  # Has H2O
c = 'light' in s # Has light
d = len(s) == 3  # Only those 3
output_sugar = a and b and c and d
if output_sugar:
  print('C6H12O6+6O2') # output text
elif inp == 'r':
  print(open(__file__).read()) # quine
else:
  print(inp) # cat program

```

# Scoring

\- i.e. lowest byte count 'wins'
(as bigger ~~programs~~ cells will have less surface-to-volume ratio and thus make it harder to intake energy)

### Cell\`s Life: S̵̲̿̈́ę̴̬̓r̷͈͑͜i̵̝̔̇ė̴̛̯̹s̶̢͋̓

?̶̦͓̰̻̀ ̶̳͇͚̆Ŝ̸̭̤̱̅̔̚t̷̜̩̯̀̿à̶͑͝y̴͚̼͇͊͒̚ ̷̍ͅt̶̮̥̥͌̂ͅủ̵͎n̸͔̉ē̷̊̕d̴̟̭͎͐̈́͝ ̸̗͇̓͗̚?̸̡̗̲͑͛͌

# Answer
> 3 votes
# Ruby `-p`, ~~96~~ 87 bytes

```
eval q="$_=%w[6CO2 6H2O light]-$_.split(?+,3)==[]?'C6H12O6+6O2':/^r$/?'eval q=%p'%q:$_"

```

Attempt This Online!

The code is an extension of the Ruby quine

```
eval q="$><<'eval q=%p'%q"

```

The optional second argument to `split` is needed to avoid false positives on inputs like `6CO2+6H2O+light+`. The check for an input of `r` uses a bare regex literal as a conditional, saving a byte over the more obvious `$_==?r` but provoking a warning from the interpreter.

# Answer
> 2 votes
# Jelly, ~~77~~ 70 bytes

```
“+“6CO2+6H2O+light r“C6H12O6+6O2“ḣ2œṣṢjɗḲi¥@ƭƒ³ị3ị,Ṿ;⁾0ị,⁾vƊƊƲ³ṭƊ”0ịvƊ

```

Try it online!

A full program link taking a string argument and printing a string argument. This currently feels a little verbose for a Jelly answer!

# Answer
> 1 votes
# 05AB1E, 98 bytes

```
1"D34çýU'rQiXë“6CO26H2O“2ä'‡Žªœ'+ýIåi“C6H12O6+6O2"D34çýU'rQiXë“6CO26H2O“2ä'‡Žªœ'+ýIåi“C6H12O6+6O2

```

Outputs the `C6H12O6+6O2` with two instead of one trailing newlines. Could be fixed in +2 bytes by adding  after both `C6H12O6+6O2` in the program.

Try it online.

**Explanation:**

```
1                   # Push a 1
 "..."              # Push the program's source code
      D             # Duplicate it
       34ç          # Push 34, and convert it to a character with this codepoint: '"'
          ý         # Join the stack with '"'-delimiter
           U        # Pop and store this quine-string in variable `X`
'rQi               '# If the (implicit) input is "r":
    X               #  Push quine-string `X`
                    #  (which is output implicitly with trailing newline)
   ë                # Else:
    “6CO26H2O“      #  Push string "6CO26H2O"
     2ä             #  Push it into two equal-sized parts: ["6CO2","6H2O"]
       '‡Ž         '#  Push dictionary word "light"
          ª         #  Append it to the pair
           œ        #  Get all six permutations of this triplet
            '+ý    '#  Join each inner triplet with "+"-delimiter
    Iåi             #  If the input is in this list:
       “C6H12O6+6O2
                    #   Push string "C6H12O6+6O2\n"
                    #   (which is output implicitly with trailing newline)
                    #  (implicit else)
                    #   (implicitly output the implicit input with trailing newline)

```

# Answer
> 1 votes
# JavaScript (Node.js), 79 bytes

```
f=x=>x.split`+`.sort().join`+`=='6CO2+6H2O+light'?'6O2+C6H12O6':x=='r'?'f='+f:x

```

Try it online!

Nothing special

# Answer
> 0 votes
# Python 3, ~~164~~ 142 bytes

```
m=r'm=%r;a=input();print("C6H12O6+6O2"if{"6H2O","6CO2","light"}==set(a.split("+"))else"m=r\x27"+m+"\x27;exec(m%%m)"if a=="r"else a)';exec(m%m)

```

Here is a Python quine that meets all the requirements.

# Answer
> 0 votes
# Google Sheets, 109 bytes

`=ifs(""=A1,,"6CO2+6H2O+light"=join("+",sort(tocol(split(A1,"+")))),"C6H12O6+6O2","r"=A1,formulatext(F1),1,A1)`

Put the input in cell `A1` and the formula in cell `F1`.

Uses a `cat $0` type quine, so non-competing.

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


title: Print the ASCII Code page

text:
# Question
Title: Print the ASCII Code page
# Goal

You have to print the ASCII printable characters' code page (0x20-0x7E). The output should look like this:

```
 !"#$%&'()*+,-./
0123456789:;<=>?
@ABCDEFGHIJKLMNO
PQRSTUVWXYZ[\]^_
`abcdefghijklmno
pqrstuvwxyz{|}~

```

# Rules

* The output should be **exactly** like shown above, but trailing whitespace is OK.
* **No builtins that trivialize the question** *(e.g. the ones that print the ASCII table)* **!** They can be posted for documentation purposes, but will not be in the leaderboards.
* Standard rules for I/O and loopholes apply.
* Lowest bytecount wins.

## Good Luck!

*P.S. This challenge is well-known, but a straight "print every single printable ASCII character" has somehow never been done here.*

# Answer
# Python 3, 42 bytes

```
print(('%c'*16+'\n')*6%(*range(32,127),9))

```

Try it online!

Includes a trailing tab on the last line and a trailing newline.
> 17 votes

# Answer
# Python 3, 52 bytes

```
for i in range(95):print(chr(i+32),end='\n'[~i%16:])

```

Try it online!
> 15 votes

# Answer
# Prelude, ~~50~~ 42 bytes

```
88+
6(1-) v^^(  1-++!)^6-!)
1- v+(1-) v(1-

```

Try it online!

### Explanation

```
88+
6(1-)
1- v+

```

Push \\$16\\$ to Voice 1 and \\$95\\$ to Voice 3.

```

       v^^
      (1-)

```

For each value from \\$95\\$ down to \\$1\\$, push that value and two copies of \\$16\\$ to Voice 2. When the loop ends, the stack in Voice 2 is `[..., 0, 0, 0, 95, 16, 16, 94, 16, 16, ..., 1, 16, 16]`.

```

         (  1-++!     )

```

For each triplet of values in Voice 2, sum them and subtract \\$1\\$, then print the result as an ASCII character...

```

                 )
          v(1-

```

in groups of 16...

```

                  ^6-!

```

with a newline appended to each group.

Printing fails on the (non-existent) 96th character because the triplet of values summed is `[0, 0, 0]`, with the result that the code attempts to convert \\$-1\\$ to ASCII and thus exits with an out-of-range error.

---

# Fugue

Fugue is a musical encoding for Prelude. *Fugascii*\*, a short trio for woodwinds, was generated from the Prelude code above using a script that I wrote for this purpose. Read all about it in this answer.

* The title is a pun on a previous Fugue composition of mine, *Fugacity*.
> 12 votes

# Answer
# Zsh, 26 bytes

```
printf %s {\ ..~}|fold -16
```

Attempt This Online!
> 10 votes

# Answer
# Piet \+ ascii-piet, ~~87~~ 82 bytes (3×28=84 codels)

*Thanks @Bubbler for -5 bytes by changing `4 dup * 2 *` to a more space efficient `8 4 *`*

```
eeeumtqcsqrrjlvuddtrjcqdjes_eeeu ?????rr?jujrnvmsjiqqc _eeuu kdvtrbbbbb???vv   qq?

```

Try Piet online!

Might add a more detailed explanation later if I feel like to, but here's an explanation image generated by Bubbler's Piet interpreter for now. Can 100% be golfed, but I'm too lazy to do that right now lol.

### Explanation image

The basic algorithm is to initially push `32` to the stack, then keep incrementing and outputting the character until `127`, after which the code stops. At each iteration, it checks if the number+1 is a multiple of 16, and prints a newline if it is.

### Longer explanation

Here's the ascii piet version of the code, with newlines added for clarity:

```
eeeumtqcsqrrjlvuddtrjcqdjes_
eeeu ?????rr?jujrnvmsjiqqc _
eeuu kdvtrbbbbb???vv   qq?

```

I'll be going over the code section by section.

Initialization:

```
eeeum
eeeu
eeuu

```

Push 8, Push 4, multiply. This puts `32` onto the stack (the codepoint for space)

Top half of the loop:

```
     tqcsqrrjlvuddtrjcqdje

```

What it does:

```
Commands                              Stack          DP,     CC
dup                                   [32,32]        right   left
out (char)                            [32]           right   left
1 + Dup                               [33,33]        right   left
4 dup * dup * 2 / 1 -                 [33,33,127]    right   left
- ! !                                 [33,1]         right   left
DP+                                   [33]           down    left

```

Basically, it adds `1` to the current codepoint and checks if it is equal to `127`. If it is, then `DP+` will turn the pointer `0` times and terminate the code. Otherwise, `DP+` will turn the pointer `1` time and continue the loop.

Bottom right portion of the loop:

```

            ?jujrnvmsjiqqc
               ???vv   qq?

```

What it does:

```
Command                              Stack          DP,     CC
dup                                  [33,33]        down    left
4 dup *                              [33,33,16]     left    right
%                                    [33,1]         left    right
! 3 *                                [33,0]         left    right
1 CC+                                [33,0]         left    left
DP+                                  [33]           left    right

```

This checks if the current codepoint is a multiple of 16 (remember that we added 1 to the codepoint in the top half of the loop). If it is a multiple of 16, then `DP+` will turn the DP to face downwards. Otherwise, the DP stays facing left. This is based on the observation that all the characters before a newline all have codepoints that are 1 less than a multiple of 16.

For example, let's say that at the beginning of this portion, the stack is `[48]`. This means that the ascii `47`, or `/`, just got printed, and then that value was incremented by `1` from the top half of the loop. After taking this value modulo 16 and applied `!` on the value, the stack becomes `[48,1]`. The `1` on the stack is then multiplied by `3` which causes `DP+` to turn the DP 3 times, resulting in the DP facing down.

Bottom branch of the loop:

```
     t
     ?
     kdvtrbbbbb

```

What it does:

```
Command                              Stack          DP,     CC
1 5 dup +                            [33,1,10]      left    right
out (char) pop                       [33]           left    right

```

Basically just prints out a newline.

Top branch of the loop:

```
     t    rr
     ?????rr?

```

Nothing actually happens here. The code just passes through and enters back into the loop. One thing to note is that the reason why we did `CC+` earlier was to get through the `r` block. Before the `CC+`, the CC was facing right, but that poses a problem when we go through the `r` block, because the code will continue execution through the top left of the block, which will break the entire code. Instead, we toggle the CC once to switch it to the left, which causes the code to exit out of the block from the bottom left.

Once the top half is entered again, `dup out (char)` is ran, printing out another character, and the loop continues.

Loop exit:

```
                          s_
                           _

```

Once the loop reaches `127`, the loop is exited. `s` is essentially a noop that does nothing, and the program terminates in the `_` block.
> 7 votes

# Answer
# , 35 bytes

```
write(intToUtf8(32:126,T),1,16,,"")

```

Try it online!
> 6 votes

# Answer
# Rust, 58 bytes

```
||for i in' '..''{print!("{:
<1$}",i,i as usize%16/15+1)}
```

Attempt This Online!

## Explanation

* The answer is a closure expression implementing the `Fn()` trait.
* `print!` can pad outputs to a given length: `print!("{:x<5}", 'a')``axxxx`
* The length can come from an argument: `print!("{:x<1$}", 'a', 5)``axxxx`
* The padding char can be a raw newline in place of the `x` in this example.
* In my program, the length is either 1 (just the char) or 2 (char + newline).
> 6 votes

# Answer
# MS-DOS (.COM format), ~~33~~ ~~30~~ 26 bytes

* -3 thanks to Deadcode
* -4 by using `INT 29H` to output

Iterates through 20H and 7EH, printing each character and a line break between the 16th character of each line.

```
0000 B0 20 CD 29 40 3C 7F 74 10 A8 0F 75 F5 50 B0 0A
0010 CD 29 B0 0D CD 29 58 EB E9 C3

```

Assembly version (TASM):

```
IDEAL
P8086

MODEL   TINY
CODESEG
ORG 100H

MAIN:
    MOV  AL,20H ; Start at ' '
PRINT:
    INT  29H    ; Print character
    INC  AX     ; Increment character
    CMP  AL,7FH ; Done?
    JZ   DONE   ; Yes, exit
    TEST AL,0FH ; End of line?
    JNZ  PRINT  ; No, next character
    PUSH AX     ; Save current character
    MOV  AL,0AH ; Print CR+LF
    INT  29H
    MOV  AL,0DH
    INT  29H
    POP  AX     ; Restore current character
    JMP  PRINT  ; Next character
DONE:
    RET

END MAIN
ENDS

```
> 6 votes

# Answer
# Python 3, 71 bytes

*-2 bytes thanks to @pxeger*

```
for i in range(6):print(''.join(chr(j+i*16+32)for j in range(16-i//5)))

```

Try it online!
> 5 votes

# Answer
# Python 2, 66 bytes

```
for i in range(6):print bytearray(j+i*16+32for j in range(16-i/5))
```

Attempt This Online!

Based on @mousetail's solution; submitted as my own answer by their suggestion.
> 5 votes

# Answer
# Rust, ~~74~~ ~~72~~ ~~70~~ 64 bytes

```
(' '..'').any(|i|print!("{i}")>if i as u8%16>14{print!("
")});

```

Text contains non-printable characters so might not render correctly. @Antiip saved me some bytes.

Attempt This Online!
> 5 votes

# Answer
# Whitespace, ~~110~~ 100 bytes

```
[S S S T    T   T   T   T   N
_Push_31][N
S S N
_Create_Label_LOOP][S S S T N
_Push_1][T  S S S _Add][S N
S _Duplicate][S S S T   T   T   T   T   T   T   N
_Push_127][T    S S T   _Subtract][N
T   S T N
_If_0_Jump_to_undefined_Label][S N
S _Duplicate][T N
S S _Print_as_character][S N
S _Duplicate][S S S T   S S S S N
_Push_16][T S T T   _Modulo][S S S T    T   T   T   N
_Push_15][T S S T   _Subtract][N
T   T   N
_If_neg_Jump_to_Label_LOOP][S S S T S T S N
_Push_10_\n][T  N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

```

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).

**Explanation in pseudo-code:**

```
Integer n = 31
Start LOOP:
  n = n + 1
  If (n==127):
    Stop program with error by jumping to undefined Label
  Print n as character to STDOUT
  If (n modulo 16 < 15):
    Go to next iteration of LOOP
  Print '\n'
  Go to next iteration of LOOP

```
> 5 votes

# Answer
# brainfuck, ~~64~~ 86 bytes

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

```

Try it online!

No longer prints 0x7f as the last character.

With many thanks to @Jiří for the fix.
> 5 votes

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

-4bytes thanks to Traws!

```
`0:`c$6 16#32+!95

```

It's my first answer in K! So there might be some optimizations ^^

```
`0:`c$6 16#32+!95
           32+!95 / Creates an array from 32 to 126
      6 16#       / Reshapes it to 16 columns and 6 lines (16 can me replaced by 0N)
   `c$            / For each elements of this array/matrix, convert the int to a char
`0:               / Print the result whitout ( and "

```

Try it online!
> 4 votes

# Answer
# x86-16 machine code, PC DOS, ~~24~~ 19 bytes

```
00000000: b020 bb0a 0daa 40a8 0f75 0393 ab93 3c7e  . ....@..u....<~
00000010: 7ef3 c3                                  ~..

```

Listing:

```
B0 20           MOV   AL, 20H       ; starting codepoint
BB 0D0A         MOV   BX, 0D0AH     ; CR/LF chars
            CP_LOOP:
AA              STOSB               ; write AL to buffer
40              INC   AX            ; increment to next char
A8 0F           TEST  AL, 0FH       ; is end of line?
75 03           JNZ   CP_NEXT       ; jump if so
93              XCHG  AX, BX        ; save current codepoint
AB              STOSW               ; write CR/LF to buffer
93              XCHG  AX, BX        ; restore codepoint
            CP_NEXT:
3C 7E           CMP   AL, 07EH      ; <= 7EH?
7E F3           JLE   CP_LOOP       ; if so, keep looping
C3              RET                 ; return to caller

```

Using @PeterCordes's suggestion to write to an output buffer instead of direct to console.

Callable function, output to string buffer `ES:[DI]`.
> 4 votes

# Answer
# x86-32 machine code (Linux executable) 27 bytes

cut-down NASM listing: Address | machine code | source

```
                   global _start
                   _start:            ; Linux processes (and thus static executables) start with registers zeroed, except ESP
                   asciitable:
 00 B020            mov al, ' '
 02 B20A            mov dl, 0xa
 04 89E7            mov edi, esp      ; space above ESP on the stack is argc, argv[] and env[] array elements, and the env strings.  We overwrite that.
                   .loop:
 06 AA              stosb
 07 40              inc  eax            ; there is no branch condition for AF, the half-carry flag :/
 08 A88F            test al, 0x8f       ; detect mod16 and when we've gone past printable
 0A 7503            jnz .nonewline
 0C 92              xchg  eax, edx
 0D AA              stosb
 0E 92              xchg  eax, edx
                   .nonewline:
                    ; FLAGS still set from earlier TEST
 0F 79F5            jns  .loop               ; stop at 0x80, beyond what the syscall uses
                     ; mov [edi-1], 0xa      ; no trailing newline

 11 B004            mov  al, 4   ; __NR_write
                    ; ebx=0 from process startup; writing to stdin happens to work on a terminal
 13 89E1            mov  ecx, esp
 15 8D5060          lea  edx, [eax-4 + 0x7f-0x20 + 5]  ; exclusive range, 5 newlines; final line does not end with newline as whitespace isn't required
 18 CD80            int  0x80    ; write(0, ecx, 100)

                   ; mov  eax,1      ; exit(ebx)
                   ; int  0x80
 1A CC              int3  ; abort program

```

Fill bytes into a buffer (overwriting stack memory above ESP, starting with argc, argv\[\], and into env\[\]). We go a bit beyond 0x7e because that makes the stop condition cheaper, but those bytes aren't printed: we have to generate an explicit length in EDX anyway, so we just omit it.

We make one `write(0, buf, 100)` system call. `0` is STDIN\_FD, but on a normal xterm/konsole/gnome\_terminal, FD 0,1, and 2 are all read+write duplicates of the same file description. So we save 1 byte for `inc ebx`. If you want to pipe the output into something to hexdump for example, `./asciitable 0>&1 | hexdump -C`

Instead of existing cleanly, we use `int3` to raise a debug exception, resulting in the OS delivering SIGTRAP, killing the process. A typical shell will then print `Trace/breakpoint trap (core dumped)`, but that's the shell, not this program. This saves 3 bytes vs. `mov al, 1` / `int 0x80` (the upper bytes of EAX are zeroed, unless `write` returned an error).

I considered letting execution just fall off the end (to probably `00 00` padding added by the linker, which decodes as `add [eax], al` and will segfault), but we're already stretching things a bit by only counting the `.text` section of the executable, not the whole file size. (Unlike a DOS `.com`, there *is* metadata)

Our output doesn't end with a newline; as the question says, no trailing whitespace is required after the `0x7e` `~` character.

The mod16 detection via checking the low bits 4 of AL is fairly straightforward, but was borrowed from ErikF's the x86-16 MS-DOS answer which I read first before thinking about how I'd do it.

But to enable a `jns` as the loop branch without a separate `cmp`, we also set the MSB in our mask for `test`. That's not a spot we wanted a newline anyway. I'd hoped to be able to branch on FLAGS from `inc al` (2 bytes), but since we'd also need something for newlines, this is even better: we can now use `inc eax` (1 byte) and still branch on the MSB of AL. Using mov dl, 0xa (2B) / xchg/stosb/xchg (1B each) instead of `mov byte [edi], 0xa` (3 bytes) / `inc edi` (1 byte but clobbers FLAGS) was the key to that, saving another `test` or `cmp` for a net saving of 1 byte.

Demo:

```
$ nasm -felf32 asciitable.asm
$ ld -melf_i386 -o asciitable asciitable.o
$ ./asciitable
 !"#$%&'()*+,-./
0123456789:;<=>?
@ABCDEFGHIJKLMNO
PQRSTUVWXYZ[\]^_
`abcdefghijklmno
pqrstuvwxyz{|}~Trace/breakpoint trap (core dumped)

$ ./asciitable 0>&1 | cat  # suppresses signal diagnostic from shell
 !"#$%&'()*+,-./
0123456789:;<=>?
@ABCDEFGHIJKLMNO
PQRSTUVWXYZ[\]^_
`abcdefghijklmno
pqrstuvwxyz{|}~peter@volta:/tmp$

$ ./asciitable 0>&1 | hexdump -C
00000000  20 21 22 23 24 25 26 27  28 29 2a 2b 2c 2d 2e 2f  | !"#$%&'()*+,-./|
00000010  0a 30 31 32 33 34 35 36  37 38 39 3a 3b 3c 3d 3e  |.0123456789:;<=>|
00000020  3f 0a 40 41 42 43 44 45  46 47 48 49 4a 4b 4c 4d  |?.@ABCDEFGHIJKLM|
00000030  4e 4f 0a 50 51 52 53 54  55 56 57 58 59 5a 5b 5c  |NO.PQRSTUVWXYZ[\|
00000040  5d 5e 5f 0a 60 61 62 63  64 65 66 67 68 69 6a 6b  |]^_.`abcdefghijk|
00000050  6c 6d 6e 6f 0a 70 71 72  73 74 75 76 77 78 79 7a  |lmno.pqrstuvwxyz|
00000060  7b 7c 7d 7e                                       |{|}~|
00000064

$ strace ./asciitable 0>/dev/null
execve("./asciitable", ["./asciitable"], 0x7ffc63d167c0 /* 55 vars */) = 0
[ Process PID=2670503 runs in 32 bit mode. ]
strace: WARNING: Proper structure decoding for this personality is not supported, please consider building strace with mpers support enabled.
write(0, " !\"#$%&'()*+,-./\n0123456789:;<=>"..., 100) = 100
--- SIGTRAP {si_signo=SIGTRAP, si_code=SI_KERNEL} ---
+++ killed by SIGTRAP (core dumped) +++
Trace/breakpoint trap (core dumped)

```

Try it online! with an `inc ebx` added so it writes to stdout and thus shows up in the tio.run output pane. IDK why it didn't show in the debug pane. (32-bit code supported by having FASM make an executable directly, instead of NASM.)

## TODO: a function instead of program, filling a buffer

We'd obviously save the syscall code, but could no longer write past the end of the actual stop point. So would need maybe 1 more byte in the loop to go back to `cmp al, 0x7e` / `jne` as the loop condition.
> 4 votes

# Answer
# 05AB1E, 10 bytes

**Without builtin:**

```
₃L31+çJ6ä»

```

Try it online.

**With builtin (5 bytes):**

```
žQ6ä»

```

Try it online.

**Explanation:**

```
₃L          # Push a list in the range [1,95]
  31+       # Add 31 to each
     ç      # Convert the codepoint-integers to ASCII characters
      J     # Join the list together to a string
       6ä   # Split it into 6 parts
         »  # Join by newlines
            # (after which the result is output implicitly)

žQ          # Push a string of all ASCII characters
  6ä»       # Same as above

```
> 3 votes

# Answer
# Vyxal 2.14.1, 9 bytes

```
kPð+s16ẇ⁋

```

Try it Online!

So turns out `kP` isn't *actually* all of printable ascii - it's missing the space character, and it isn't in the right order either, meaning that for the purposes of this challenge, it shouldn't be banned, as it doesn't print "the ascii table" and it isn't exactly "trivial" either.

(And if it isn't allowed, then that's grounds enough for VTCing this challenge as needs details or clarity, because "trivialising the challenge" isn't objectively defined - there's an argument to be made that `kPð+s` isn't a trivial built-in).

## Explained

```
kPð+s16ẇ⁋
kPð+       # a string of 0-9a-Z + python's string.punctuation + space
    s      # sorted to be in printable ascii order
     16ẇ   # split into parts of length 16
        ⁋  # joined on newlines

```

## Vyxal, 5 bytes

```
kP6/⁋

```

Try it Online!

Bug fixes make this 5 bytes in reality.
> 3 votes

# Answer
# Burlesque, 18 bytes

```
@!~r@' +]16co)++un

```

Try it online!

```
@!~  # Push ! and ~ to stack
r@   # Range between them
' +] # Prepend " "
16co # Chunks of 16
)++  # Concat
un   # Intercalate newlines between blocks and join

```
> 3 votes

# Answer
# BQN, 12 bytes

```
6‿16⥊' '+↕95

```

Try it at BQN REPL

Output has a trailing space character.

BQN's affine character space is quite neat here: adding a number to a character gives another character. So: create a range from zero to 95 (`↕95`), add it to the space character (`' '+`), and reshape to 6-row, 16-column format (`6‿16⥊`).

---

# BQN, 26 bytes

```
@+100⥊⍉(32+⍉6‿16⥊↕95)∾6⥊10

```

Try it at BQN REPL

Longer version with output string that is truly "**exactly** like shown above", written before the edit allowing trailing whitespace.
Creates a transposed array of character values (`32+⍉6‿16⥊↕95`), appends a newline value 10 to each column (`∾6⥊10`), re-transposes () & extracts the first 100 values (`100⥊`), and finally converts to characters (`@+`).
> 3 votes

# Answer
# PowerShell Core, 35 bytes

```
-join(' '..'~')-split'(.{16})'-ne''

```

Try it online!

```
     (' '..'~')                     # create a list of characters from <space> to ~
-join                               # join the list to a single string
               -split'(.{16})'      # split the string every 16 chars ...
                              -ne'' # ... and let only non-empty strings pass.

```
> 3 votes

# Answer
# V (vim), 10 bytes

```
¬ ~5ñ16|á

```

Try it online!

Explanation:

```
¬               # Insert characters between the code points...
  ~             #   "space" and "~"
   5ñ           # 5 Times...
     16|        #   Go to the 16th character on this line
        á<cr>   #   Append a newline

```

Hexdump:

```
00000000: ac20 7e35 f131 367c e10d                 . ~5.16|..

```
> 3 votes

# Answer
# Perl 5, 30 bytes

```
say map$/x!($_%16).chr,32..126

```

Try it online!
> 3 votes

# Answer
# sed `-r`, 94 bytes

```
s/.*/ABCDEFGHIJKLMNO\nPQRSTUVWXYZ/
saa !"#$%\&'()*+,-./\n0123456789:;<=>?\n@&[\\]^_\n`\L&{|}~a

```

Try it online!

This is probably the best that can be done in sed, which has no functionality for ranges of characters. The main byte saving is in the fact we can generate `ABCDEFGHIJKLMNOPQRSTUVWXYZ` and then use `\L` to get the lowercase version.
> 3 votes

# Answer
# PHP, ~~43~~ 40 bytes

```
<?=chunk_split(join(range(' ','~')),16);

```

Simply outputs the expected text, without any trailing newlines.

Just run `php file.php` and it should produce the output.

Try it on: https://onlinephp.io/c/013ce

---

Thanks to Steffan for -3 bytes.
> 3 votes

# Answer
# , 38 bytes

```
intToUtf8(rbind(matrix(32:126,16),10))

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Extended), 12 bytes

```
6 16⍴' '…'~'

```

Try it online!

`' '…'~'` inclusive range from space to tilde

`6 16⍴` cyclically **r**eshape into the required number of rows and columns
> 2 votes

# Answer
# GeoGebra, ~~68~~ 67 bytes

```
UnicodeToText(Flatten(Zip(If(Mod(a,16)>14,{a,10},{a}),a,32...126)))

```

Text is shown on the graph.

Might be golfable with some different strategy, but I'm not too experienced with GeoGebra.

Try It Online!
> 2 votes

# Answer
# MathGolf, 10 bytes

```
♣⌡╒T≥$y☻/n

```

Try it online.

**Explanation:**

```
♣           # Push 128
 ⌡          # Decrement it by 2 to 126
  ╒         # Pop and push a list in the range [1,126]
   T        # Push 31
    ≥       # Pop and remove the first 31 items from the list
     $      # Convert each codepoint-integer to a character
      y     # Join the list to a string
       ☻    # Push 16
        /   # Pop and split the string into parts of size 16
         n  # Join the list by newlines
            # (after which the entire stack is output implicitly as result)

```
> 2 votes

# Answer
# jq `-nr`, 39 bytes

```
[range(32;127)]|implode|scan(".{1,16}")
```

Attempt This Online!

The best I can do without regex is 40 bytes:

```
16*range(2;8)|[.+range(16-./99)]|implode
```

Attempt This Online!
> 2 votes

# Answer
# C (clang), ~~51~~ \\$\cdots\\$ ~~49~~ 48 bytes

```
f(c){for(c=32;putchar(c)<126;++c%16||puts(""));}

```

Try it online!

*Saved ~~a~~ 2 bytes thanks to tsh!!!*
*Saved a bytes thanks to ovs!!!*
> 2 votes

# Answer
# Charcoal, 12 bytes

```
ＵＴ⪪⪫…· ¦~ω¹⁶

```

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

```
ＵＴ

```

Disable automatic padding (would normally output a trailing space on the last line).

```
⪪⪫…· ¦~ω¹⁶

```

List the characters from  to `~` inclusive, join them together, split into groups of 16, and implicitly print each group on its own line.

Save 6 bytes by using the builtin `γ` in place of `⪫…· ¦~ω`. Try it online! Link is to verbose version of code.
> 2 votes

# Answer
# Factor, 36 bytes

```
32 126 [a,b] 16 group "\n"join write

```

Attempt This Online!
> 2 votes

# Answer
# Pyth, ~~15~~ 9 bytes

```
jsMc6rd\

```

Try it online!

There's a literal DEL character after the `\`.

```
jsMc6rd\
     rd\  Half-inclusive string range from ' ' (space) to DEL
   c6     Chop into 6 equal-sized lists (last chunk is smaller)
 sM       Join each list on '' (empty)
j         Join on newlines, implicitly output

```
> 2 votes

# Answer
# Raku, 33 bytes

```
.say for (' '..'~').join.comb(16)

```

Try it online!
> 2 votes

# Answer
# Pip, 15 bytes

```
P*C:32,127<>16u

```

Try It Online!

### Explanation

```
P*C:32,127<>16u
    32,127       Range(32, 127)
          <>16   Group into chunks of size 16 (with the last one being shorter)
  C:             Convert to characters
P*               Print each sublist (concatenated together, by default)
              u  Suppress autoprinting of the last expression

```

Or, with the `-l` flag to handle the output formatting, it would be 12 bytes:

```
C:32,127<>16

```

### Using built-in

`PA` is a string containing all printable ASCII characters, so:

```
PA<>16Jn

```

Or, with the `-l` flag:

```
PA<>16

```
> 2 votes

# Answer
# Ruby, ~~53~~ 44 bytes

*Thanks user for telling me about `each_slice`, saving 9 bytes!*

```
(' '..'~').each_slice(16).each{|x|puts x*""}

```

Try it online!

My first time golfing in Ruby lol, just wanted to try a new language :D . Tell me if there are any golfs, I'm anticipating a lot!
> 2 votes

# Answer
# stacked, 23 bytes

```
95:>32+16 chunk chr out

```

Try it online!

Slightly shorter than the more obvious 24 bytes:

```
32 126|>16 chunk chr out

```

## Explanation

```
95:>32+16 chunk chr out
95:>                       the range of numbers from 0 to 94 inclusive
    32+                    add 32 to each
       16 chunk            split into chunks of 16
                chr        convert each number to a character
                    out    output it

```

stacked's default output behavior with `out` for 2D character arrays is exactly joining them, and produces the correct output.
> 2 votes

# Answer
# Regenerate `-a -s=`, 45 bytes

```
[ -/]|
|[0-?]|
|[@-O]|
|[P-_]|
|[`-o]|
|[p-~]

```

Attempt This Online!

### Explanation

The `-a` flag requests all possible matches; the `-s=` flag sets the separator between matches to empty string. Then the regex is just a big alternation: "match any character from  to `/`, or a newline, or any character from `0` to `?`, or a newline, or..." The regex always matches one character, and the `-a` flag outputs all of them.
> 2 votes

# Answer
# Brainfuck \+ head + sh, 65 + 10 bytes

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

Execute `<brainfuck-program>|head -c-2` (see meta).

`head` removes a trailing `\del` char of the brainfuck program output (as noted by @mousetail).

Attempt This Online!
> 2 votes

# Answer
# Piet \+ ascii-piet, 59 bytes (4×26=104 codels)

```
tliusqrfvrtqqqqijsmva???Bt  t?sd???vmjftrqaaaaqrsb_t eTt ee

```

Try Piet online!

### How it works

```
4 dup * dup +         Initialize n to 32
Loop:
    dup outC          [n] Print as char
    1 + dup dup       [n n n] Add 1 and make two more copies
    4 dup * % !       [n n n%16==0] Is this number divisible by 16?
    CC+               [n n] If so,
        5 dup + outC        Print newline
    5 dup dup * * >   [n n>125] Is this number greater than 125?
    ! DP+             [n] If not, go back to start of Loop
outC                  Otherwise, print n (126) and exit

```
> 2 votes

# Answer
# Kotlin, ~~80~~ ~~72~~ 56 bytes

### 56 bytes versuin

```
(' '..'~').chunked(16).flatMap{it+"\n"}.joinToString("")

```

Directly using a char range instead of an integer range.

Try it online!

### 72 bytes version

```
(32..126).chunked(16).flatMap{it.map{it.toChar()}+"\n"}.joinToString("")

```

Try it online!

### 80 bytes version

```
(32..126).chunked(16){it.joinToString(""){""+it.toChar()}+"\n"}.joinToString("")

```

Try it online!
> 2 votes

# Answer
# Nibbles, 7.5 bytes (15 nibbles)

```
`/16+' '`,95

```

```
`/16+' '`,95
        `,95    # range from 0 to 95
    +' '        # add each to a space character
`/16            # and split into chunks of 16

```

---

# Nibbles, 5 bytes (10 nibbles)

```
`/16>>`<@

```

Uses the special value assigned to `@` when input is empty, corresponding to a list of ascii characters including newline, in a non-standard order.

`/16>>`<@
        @       # " abcdefghijklmnopqrstuvwxyz.,!?_"
                # + newline +
                # "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-+:;\"'~`@#$%^&*()[]{}<>\\/=|"
      `<        # sort
    >>          # remove first item (newline)
`/16            # and split into chunks of 16
```
</code></pre>
> 2 votes

# Answer
# Vim, 50 bytes

```
i<C-r>=joi<Tab>m<Tab>r<Tab>32,126),'"<C-v><C-v>".v:val'),"")
<Esc>qq16|a
<Esc>q4@q

```

Try it online!

As pointed out by @Ray, if you have version 8.1.26 or newer, you'll have to replace `r<Tab>` with `rang<Tab>` for 53 bytes.

### Explanation

```
i<C-r>=                                                       # Insert the result of:
               m<Tab>             ,                    )      #   Map...
                                   '"<C-v><C-v>".v:val'       #     Convert to char...
                     r<Tab>32,126)                            #     over range [32,126]
       joi<Tab>                                         ,"")  #   Join with empty strings
<Esc>
     qq                                                       # Record macro @q:
       16|                                                    #   Go to 16th character
          a                                                   #   Add a newline
<Esc>q
      4@q                                                     # Run macro @q 4 times

```
> 2 votes

# Answer
# PARI/GP, 43 bytes

```
for(i=1,95,printf("%c",i+31);i%16||print())
```

Attempt This Online!

---

# PARI/GP, 44 bytes

```
for(i=2,7,print(Strchr([s=16*i..s+15-i\7])))
```

Attempt This Online!
> 1 votes

# Answer
# Clojure, ~~72~~ 63 bytes

```
(doseq[x(range 32 127)](print(str(char x)({15 \
}(rem x 16)))))

```

Try it online!
> 1 votes

# Answer
# Retina, 19 bytes

```

6*$(16*1¶
Y`1` -~_

```

Try it online! Explanation:

```

6*$(16*1¶

```

Insert 6 rows of 16 `1`s.

```
Y`1` -~_

```

Cyclically transliterate the first 95 `1`s to the range from  to `~` and delete the 96th.
> 1 votes

# Answer
# Husk, 11 bytes

```
↓2C16mcŀ127

```

Try it online!

```
       ŀ127 # range from zero to 126
     mc     # map across this & get characters
  C16       # cut into sublists with length 16
↓2          # drop the first 2 of them

```
> 1 votes

# Answer
# MATL, 8 bytes

```
'~':16e!

```

Try it online! Outputs a trailing whitespace (to make the last row have the same length as the others).

### How it works

```
'~'   % Push this character
:     % Range from space to that character, including both. Gives a character vector
16e   % Format as a 16-row character matrix, in major-column order. Pads with
      % character 0 at the end
!     % Transpose
      % Implicit display. Character 0 is displayed as space

```
> 1 votes

# Answer
# Python 2, 68 bytes

```
l=''.join(chr(x+32)for x in range(95))
while l:print l[:16];l=l[16:]

```

Try it online!
> 1 votes

# Answer
# Jelly, 10 bytes

```
32r126Ọs⁴Y

```

**Try it online!**

5 if we can just use our langauage's features:

```
ØṖs⁴Y

```

### How?

```
32r126Ọs⁴Y - Link: no arguments
32         - 32                }
   126     - 126               }
  r        - inclusive range   }
      Ọ    - cast to ordinals  } - together this is the same as ØṖ yields
        ⁴  - 16
       s   - split into chunks of length (up to 16)
         Y - join with newline characters

```
> 1 votes

# Answer
# Bubblegum, 102 bytes

```
00000000: 5350 5452 5651 5553 d7d0 d4d2 d6d1 d5d3  SPTRVQUS........
00000010: e732 3034 3236 3135 33b7 b0b4 b2b6 b1b5  .20426153.......
00000020: b3e7 7270 7472 7671 7573 f7f0 f4f2 f6f1  ..rptrvqus......
00000030: f5f3 e70a 080c 0a0e 090d 0b8f 888c 8a8e  ................
00000040: 898d 8be7 4a48 4c4a 4e49 4d4b cfc8 ccca  ....JHLJNIMK....
00000050: cec9 cdcb e72a 282c 2a2e 292d 2baf a8ac  .....*(,*.)-+...
00000060: aaae a9ad 0300                           ......

```

Try it online!

For some reason, compressing it made it actually a bit larger than the original string.
> 1 votes

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

```
for(i=33,a=' ';i<129;a+=Buffer([i++]))i%16||console.log(a,a='')

```

Attempt This Online!
> 1 votes

# Answer
# Haskell, 65 bytes

```
_#[]=[]
n#x=take n x:n#drop n x
main=putStr$unlines$16#[' '..'~']
```

Attempt This Online!
> 1 votes

# Answer
# Forth (gforth), 52 bytes

```
: f 127 32 do i emit i 16 mod 15 = if cr then loop ;

```

Try it online!

## Explanation

Loops from 32 to 127 (end is non-inclusive). Outputs the ascii char for each number, if index % 16 == 15, outputs a newline.

## Code Explanation

```
: f            \ start a new word definition
  127 32       \ set up loop bounds
  do           \ start a new counted loop
    i emit     \ output the ascii character for the current loop index
    i 16 mod   \ get index modulo 16
    15 =       \ check if result is equal to 15
    if cr then \ if it is, output a newline
  loop         \ end the counted loop
 ;             \ end the word definition

```
> 1 votes

# Answer
# *Acc!!*, 67 bytes

```
Count i while i-100 {
1/((i+1)%17+1)
Write 10*_+(i+32-i/17)*(1-_)
}

```

Try it online!

### Explanation

We run a single loop that outputs one character each time, using math to switch between ASCII characters and newlines.

The loop index `i` runs from 0 through 99. We want to print newlines at indices 16, 33, 50, 67, and 84--that is, where `(i+1)%17` is zero. With no comparison operators in *Acc!!*, we use integer division instead: when `(i+1)%17` is zero, `1/((i+1)%17+1)` is one, and it is zero otherwise. We store this quantity in the accumulator.

Now if the accumulator value is one, we want to write a newline, and if it is zero, we want to write something else. This is easily accomplished by multiplying the two quantities by `_` and `(1-_)` respectively, and adding the results: `Write 10*_+(...)*(1-_)`. It only remains to calculate the ASCII character's codepoint. At first, it is just `i+32`, but we need to adjust for the newlines. The number of newlines printed so far is `i/17`, so subtracting this from the index gives us the correct codepoint formula: `i+32-i/17`.

---

A more straightforward solution with two loops is 73 bytes:

```
Count i while i-6 {
Count j while j-16+i/5 {
Write i*16+32+j
}
Write 10
}

```
> 1 votes

# Answer
# \*\>\<\>, 53 bytes

```
e9*&1f+2*   v
v;?=&:&:+1o:<
\:1f+%?!`   /
        `ao

```

Try it online!

Unfortunately, I feel like a lot of these bytes are spent setting, storing, and checking if we're at `126` yet, but I'm unsure of a better way of accomplishing this.

```
e9*&            push 126 to the stack, and pop it into a register
    1f+2*       push 32 to the stack
            v   Change IP direction downwards

            <   Change IP direction to the left
          o:    Duplicate the top of the stack, then pop it to STDOUT as a char
       :+1      Add one to the value on the top of the stack, and duplicate it
    &:&         Pop the register back onto the stack, duplicate it, then pop that into the register
 ;?=            If our two duplicated values match, end execution
v               Change IP direction downwards

\               Mirror IP to the right
 :              Duplicate the top of the stack
  1f+           Put 16 on the stack
     %          Get the modulus of our counter and 16
      ?!`       If the result is 0, drop down a line, and
         ao         Print a newline
        `           And raise back up a line
            /   Else, mirror the IP up

```
> 1 votes

# Answer
# Fig, \\$17\log\_{256}(96)\approx\\$ 13.993 bytes

**Without printable ascii builtin**

```
nOC+32r95 16'+xcn

```

Try it online!

**With printable ascii builtin \\$10\log\_{256}(96)\approx\\$ 8.231 bytes**

```
ncp16'+xcn

```

Try it online!

```
nOC+32r95 16'+xcn
      r95          # range [0,95)
   +32             # add 32 to each, range [32,126)
  C                # convert each element to str
 O                 # join by nothing
n         16       # every 16th element, apply the function
            '+     # add
               cn  # newline
              x    # to the element

ncp16'+xcn
 cp                # printable ascii
n  16'+xcn         # same as above

```
> 1 votes

# Answer
# Julia 1.0, ~~69~~ 63 bytes

```
map(i->println(String(reshape([' ':'~';' '],(16,6))[:,i])),1:6)

```

Try it online!

-6 bytes thanks to @amelies: `' ':'~'` is a valid range in Julia; no need to convert from integers
> 1 votes

# Answer
# Julia 1.0, ~~53~~ 52 bytes

```
0:16:80 .|>n->(prod(' ':'~')*" ")[n+1:n+16]|>println

```

Try it online!
> 1 votes

# Answer
# \>\<\>, ~~30~~ 29 bytes

```
84*v
%?!\:e9*)?;:o1+:82*
ao \

```

Try it online
> 1 votes

# Answer
# POSIX Shell Command Language + Utilities + V10 UNIX seq, 54 bytes

```
printf %b `seq -f'obase=8;"\";%g' 32 126|bc`|fold -w16

```

Self-explanatory: seq generates lines in the `obase=8;"\";100` format, bc turns them into lines in the `\144` format, printf expands them and pastes them together, fold wraps the output at 16 columns

There is, of course, trouble with seq. The minimal seq required here is Version 10 AT&T UNIX (and, hence, Plan 9), V8-V9 won't work since they take a **-p***picture* argument. Realistically this is not a problem since all modern systems include a V10-compatible seq, but.

Transcript of test cases:

```
$ cat b.sh; echo; wc -c b.sh
printf %b `seq -f'obase=8;"\";%g' 32 126|bc`|fold -w16
54 b.sh
$ ./b.sh; echo
 !"#$%&'()*+,-./
0123456789:;<=>?
@ABCDEFGHIJKLMNO
PQRSTUVWXYZ[\]^_
`abcdefghijklmno
pqrstuvwxyz{|}~
$ ./b.sh | hd
00000000  20 21 22 23 24 25 26 27  28 29 2a 2b 2c 2d 2e 2f  | !"#$%&'()*+,-./|
00000010  0a 30 31 32 33 34 35 36  37 38 39 3a 3b 3c 3d 3e  |.0123456789:;<=>|
00000020  3f 0a 40 41 42 43 44 45  46 47 48 49 4a 4b 4c 4d  |?.@ABCDEFGHIJKLM|
00000030  4e 4f 0a 50 51 52 53 54  55 56 57 58 59 5a 5b 5c  |NO.PQRSTUVWXYZ[\|
00000040  5d 5e 5f 0a 60 61 62 63  64 65 66 67 68 69 6a 6b  |]^_.`abcdefghijk|
00000050  6c 6d 6e 6f 0a 70 71 72  73 74 75 76 77 78 79 7a  |lmno.pqrstuvwxyz|
00000060  7b 7c 7d 7e                                       |{|}~|
00000064

```

Here's a **100**-byte fully-standards-conformant version, same output:

```
i=32
printf %b $(while [ $i -le 126 ]
do
printf %s\\n 'obase=8;"\";'$i
i=$((i+1))
done|bc)|fold -w16

```
> 1 votes

# Answer
# Thunno `N`, \\$5\log\_{256}(96)\approx\\$ 4.12 bytes

```
zC6AP

```

Attempt This Online!

#### Explanation

```
zC6AP   # Full program. No inputs.
zC      # Push the ASCII codepage as a string
  6AP   # Split into 6 chunks
        # The N flag automatically joins by newlines
        # And then it is output implicitly

```
> 1 votes

# Answer
# , 19 bytes

```
echo _16]\u:32+i.95

```

Full program with trailing whitespace.

Attempt This Online!

```
echo _16]\u:32+i.95
               i.95  NB. range 0..94
            32+      NB. offset, 32..126
          u:         NB. convert codes to chars
     _16 \           NB. for every non-overlapping length 16 slice
        ]            NB. simply return that slice
echo                 NB. return the resulting table

```
> 1 votes

# Answer
# vim, 77 bytes

```
qqA<C-V><C-A><C-V><ESC><ESC>v0da0x0<ESC>@"0xII<C-V><C-V><ESC>A<C-V><ESC><ESC>v0d@"qxV!seq 32 126
:%norm @q
VgggJ0qq16li
<ESC>q4@q

```

`<C-V>` is 0x16. `<C-A>` is 0x01. `<ESC>` is 0x1b.

# Annotated

```
qq                                   # define macro q that changes e.g. "48" to "0" as follows:
    A<C-V><C-A><C-V><ESC><ESC>          # Change e.g. "48" to "48<INC>"
    v0d                                 # Place the above command in register "
    a0x0<ESC>@"                         # Write 0x0, then use above command to increment. Thus, "48" becomes "0x30"
    0xII<C-V><C-V><ESC>A<C-V><ESC><ESC> # Convert "0x30" to "I<C-V>x30<ESC>" (command that appends character 0x30, i.e. "0")
    v0d@"                               # Pull command into register and execute
q
xV!seq 32 126         # Populate file with numbers 32-126, one per line.
:%norm @q             # Execute macro q over each line
VgggJ                 # Join lines
0qq16li<NL><ESC>q     # Insert a newline 16 characters from the start, and record as a macro while we're at it
4@q                   # Execute that macro 4 more times

```

Try it online!
> 0 votes

# Answer
# Java (JDK), 63 bytes

```
v->{for(char c=31;++c<127;)System.out.print(c%16>14?c+"\n":c);}

```

Try it online!
> 0 votes

# Answer
# Stax, 10 bytes

```
Ç·qª>%bΓ½⌠

```

Run and debug it

## Approach

* \[0..126\]
* Keep only 95 last elements.
* Split into chunks of 16
* Print each
> 0 votes

# Answer
# Ly, 25 bytes

```
88+sp' '~R' r[l[fo,]p9`o]

```

Try it online!

This one is pretty straightforward. It uses a range command to generate the codepoints, the two loops to print them with a `\n` every 16 characters.

```
88+sp                     - stash the number 16
     ' '~R                - push codepoints from " " to "~" to the stack
          ' r             - push a blank (for DEL) and reverse stack
             [          ] - loop until the stack it empty
              l           - push 16 (from back up cell)
               [  ,]p     - loop 16 times...
                fo        - pull codepoint forward and print as char
                     9`o  - print a LF

```
> 0 votes

# Answer
# The Waterfall Model (with output extension), 166 bytes

```
[[30000,7,7,7,7,7,7,7],[3,2,2,0,0,0,7,0],[2,2,2,0,0,0,3,0],[1,0,2,300,0,0,0,0],[66,2,0,0,302,0,9,0],[4822,2,0,0,300,5100,9,0],[9,0,0,0,0,0,1,0],[29998,0,0,0,0,0,0,0]]

```

Try it online!

$$ \begin{array}{c|c|ccccccc} &start&A&B&α&β&γ&out&halt\\\hline A&3&2&2&&&&7&\\ B&2&2&2&&&&3&\\ α&1&&2&300&&&&\\ β&66&2&&&302&&9&\\ γ&4822&&&&300&5100&9&\\ out&9&&&&&&1&\\ halt&29998&&&&&&& \end{array} $$

* A and B each (upon zeroing) add 2 to both of them, and stay 1 apart. This means one of them will be zeroing every 2 steps, and externally adding 2 to that one will switch it to the other one.
* α and β cause switches to A and to B, respectively. β has a period 2 longer than α, so the time between α and β increases by 2 each cycle, and thus the number of times A zeroes increases by 1 each cycle.
* A increments the output counter and β causes it to be output as a character and reset to 0, thus outputting an increasing sequence of characters. B increases the output waterclock by a non-output-affecting value of 3 to keep it away from zero.
* γ first zeroes after the 17th zeroing of α and 10 following zeroings of A. It causes output as a character, for a line feed (ASCII 10), and increases β by 302 – equal to α's period rather than 2 greater – so that the difference between α and β does not change for this cycle.
γ has a period 17 times that of α, to add a line feed after every 16 other characters.
* The halt waterclock is never incremented, and simply counts down and ends the program after 100 characters (95 printable characters and 5 line feeds).
> 0 votes

# Answer
# GolfScript, 21 bytes

```
96,{[32+]}[/]''*16/n*

```

Try it online!
> 0 votes

# Answer
# Dyalog APL, 16 bytes

```
⎕UCS 6 16⍴31+⍳95

```
> 0 votes

# Answer
# Befunge-93, 36 bytes

```
" ">:,1+:"~"1+\`v
   ^            _@

```

Try it online!

I don't know if i can optimize this code even further than i did.

## An explanation

This code is comprised of 5 main parts:

* `" "`: Push 0x20 onto the stack.
* `:,`: Output the current character.
* `-1`: Increment the current character.
* `:"~"1+``: Compare the current character with 0x7e.
* `_@`: If current character is greater than 0x7e, end the program; else loop back to the start with `^`.
> 0 votes

# Answer
# Kotlin, ~~89~~ 73 bytes

```
print((' '..'~').chunked(16).map{it.joinToString("")}.joinToString("\n"))

```

Kotlin Playground

## Edits

* -16, inlined conversion to Char
> 0 votes

# Answer
# Knight, 31 bytes

```
;=a 32W>127aO+AaI%=a+1a 16"\"""

```

Try it online!

Unminified:

```
; = a 32
: WHILE (> 127 a)
    : OUTPUT (+ (ASCII a) (IF (% (= a (+ 1 a)) 16) "\" ""))

```
> 0 votes

# Answer
# Japt `-R`, 9 bytes

```
#_odH ¬òG

```

Test it
> 0 votes

# Answer
# Python 3, 92 bytes

```
print('\n'.join([''.join([chr(32+j+16*i)for j in range(16)])for i in range(6)]).rstrip(''))

```

Note that the blank looking character inside rstrip is DEL.

Try it online!

Explanation:

```
                [''.join([chr(32+j+16*i)for j in range(16)])for i in range(6)] # generate rows of string
      '\n'.join(                                                              ) # join with new lines
                                                                               .rstrip('') # strip the DEL out
print(
 ) # then print

```
> 0 votes

# Answer
# Pascal, 104 B

This source code complies with the ISO standard 7185 “Standard Pascal” (level 0).

```
program p(output);var c:char;begin for c:=' 'to'~'do if ord(c)mod 16=15 then writeLn(c)else write(c)end.

```

The output lacks of trailing newline.

# Extended Pascal, 94 B

In “Standard Pascal” (ISO standard 7185) width specifiers in *have* to be *positive*. That means the `n` in `write(123:n)` has to be ≥ 1. “Extended Pascal”, as laid out in ISO standard 10206, permits a zero-`write`-width format specifier. We can utilize this and “conditionally” print `chr(10)` – the newline character as used in Unixoid environments (Linux, FreeBSD, …).

```
program p(output);var c:char;begin for c:=' 'to'~'do write(c,chr(10):ord(ord(c)mod 16=15))end.

```

In Pascal, the newline character is the only character that may not appear in a string literal. Thus `chr(10)` cannot be shortened any further.
> 0 votes

# Answer
# ARM Thumb-2 machine code (Linux), 30 bytes

```
20 24 06 a1 01 22 01 34 25 07 08 bf 02 22 04 27
01 20 00 df 0c 70 7f 2c f3 d1 00 de 20 0a

```

Put this in a **read-write-execute section** at a 4 byte aligned address.

Assembler source:

```
    .syntax unified
    .arch armv7-a
    // Store in a read-write-execute section so I don't need to address
    // a different section or use the stack for my buffer
    .section ".wtext", "awx", %progbits
    .thumb
    .globl _start
    .thumb_func
    // Aligned address is necessary for the buffer
    .p2align 2, 0
_start:
    // First char
    movs    r4, #' '
.Lloop:
    // syscall setup for write(1, .Lbuf, 1)
    movs    r0, #1
    adr     r1, .Lbuf
    movs    r2, #1
    movs    r7, #4
    // Increment r4
    adds    r4, #1
    // And test r4 & 0xF to see if the NEXT char is a multiple
    // of 16. I do this with my favorite narrow instruction, LSLS,
    // where I shift out all the other bits into a dummy register and set
    // the flags.
    lsls    r5, r4, #32 - 4
    // If so, set the length to 2 to print the newline
    // if ((r4 & 0xF) == 0) length = 2;
    it      eq
    moveq   r2, #2
    // Syscall
    svc     #0
    // Store new byte into the buffer. This is why a writable .text
    // is needed.
    strb    r4, [r1]
    // Check if we are at the end (DEL), if not, loop again
    cmp     r4, #0x7f
    bne     .Lloop
.Lexit:
    // Exit with a SIGILL crash because I don't care :)
    udf     #0
    .p2align 2, 0
    // mutable buffer
.Lbuf:
    // Current char
    .byte ' '
    // Additional newline
    .byte '\n'

```
> 0 votes

# Answer
# Arturo, 42 bytes

```
loop split.every:16` `..`~`=>[print join&]

```

Try it

```
                   ` `..`~`                 ; a block of characters from space to tilde
     split.every:16                         ; split a block into groups of sixteen
loop                       =>[           ]  ; loop over every element in a block
                                        &   ; current element being looped over
                                    join    ; join block of chars to a string
                              print         ; print with newline

```
> 0 votes

# Answer
# Wolfram Language (Mathematica), 56 bytes

```
Print/@BlockMap[FromCharacterCode,32~Range~126,UpTo@16];

```

Unfortunately it doesn't work on TryItOnline due to an outdated interpreter that can't handle the `UpTo` abstraction in the `BlockMap` function call. I can offer this screenshot of my local machine:

In case that ever gets fixed (or someone knows how to work around it), here is a TIO link anyway: Try it online!

If you are not in a notebook environment the `;` at the end can be removed to save one byte.
> 0 votes

# Answer
# Uiua, ~~18~~ 17 bytes

```
≡&p⬚@ ↯∞_16+@ ⇡95

```

Try it!

```
≡&p⬚@ ↯∞_16+@ ⇡95
              ⇡95  # range from 0 to 94
           +@      # add space character
   ⬚@ ↯∞_16        # reshape into matrix 16 wide, filling excess with spaces
≡&p                # print each row

```
> 0 votes

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


title: Super Mario 64 RNG

text:
# Question
Title: Super Mario 64 RNG
# Introduction

Super Mario 64 has a heavily overcomplicated RNG, ably explained here by Pannenkoek.

I thought it might be interesting to implement it.

# Challenge

Implement the RNG function, except for the two special cases. (Not part of the below description; everything below is what you should implement.)

Input and output are both 16-bit integers.

The standard C implementation is as follows. `&` is bitwise-AND, `^` is bitwise-XOR. Shifts have higher precedence than bitwise operations, so `(s0 & 0xFF)<<1 ^ input` does the left-shift before XORing with `input`.

```
rng(input) {
    s0 = (input & 0xFF) << 8;                       // shift low byte to high
    s0 = s0 ^ input;
    input = (s0 & 0xFF) << 8 | (s0 & 0xFF00) >> 8;  // swap 8-bit halves
    s0 = (s0 & 0xFF) << 1 ^ input;
    s1 = s0 >> 1 ^ 0xFF80;
    if(s0 & 1) input = s1 ^ 0x8180;              // XOR with one of 2 constants
    else       input = s1 ^ 0x1FF4;              // depending on s0 odd or even
    return input;
}

```

In math notation, where \\$\oplus\\$ is bitwise XOR and \\$x\_L\\$ is \\$x\\$ mod 256:

\begin{equation} \text{rng}(a):= \text{let } \begin{array}{l} b = 256a\_L \oplus a \\ c = 256b\_L \oplus \lfloor b/256 \rfloor \\ d = 32256 \text{ if $c$ odd, } 57460 \text{ otherwise}\end{array} \text{ in } b\_L \oplus \lfloor c/2 \rfloor \oplus d. \end{equation}

# Example input and output

The number just before an arrow should be taken to the number just after it, so \\$f(1789)\\$ should be \\$0\\$, and \\$f(0)\\$ should be \\$57460\\$. \\$22026\\$ and \\$58704\\$ map to each other.

```
12567 -> 60400 -> 1789 -> 0 -> 57460 -> 55882 -> 50550
64917 -> 43605 -> 21674 -> 46497 -> 45151
22026 <-> 58704

```

# Rules

Shortest code wins.
Standard loopholes apply.

# Answer
> 24 votes
# x86 32-bit machine code, 21 bytes

```
89 C8 30 C4 86 C4 D1 E8 73 04 66 35 74 9E 66 35 74 E0 30 C8 C3

```

Try it online!

Uses the `fastcall` calling convention – argument in ECX, result in EAX.

In assembly:

```
f:  mov eax, ecx
    xor ah, al
    xchg ah, al
    shr eax, 1
    jnc s
    xor ax, 0x8180^0x1FF4
s:  xor ax, 0xFF80^0x1FF4
    xor al, cl
    ret

```

Simplifications used:

* The XOR constants are combined.
* The `<< 1` cancels out with the later `>> 1`.
* The check `s0 & 1` is the same as the bit shifted out by the `>> 1`.

---

# x86 16-bit machine code, 18 bytes

```
89 C8 30 C4 C1 C8 09 73 04 35 74 1E 35 74 E0 30 C8 C3

```

In assembly:

```
f:  mov ax, cx
    xor ah, al
    ror ax, 9
    jnc s
    xor ax, 0x8180^0x1FF4^0x8000
s:  xor ax, 0xFF80^0x1FF4
    xor al, cl
    ret

```

Compared to the 32-bit program, this one saves two bytes by not needing operand-size prefixes.

One more byte is saved by combining the "swap bytes" and "shift right by 1" parts into a rotation right by 9 bits. This leaves \[the bit that the original program would shift out\] at the top of the register instead; fortunately, that is the same bit that is used to choose between the XOR constants, so it can be corrected for by adjusting those constants.

# Answer
> 10 votes
# JavaScript (ES6), 45 bytes

```
n=>(q=n>>8^(n&=255))/2^n<<7^n^57460^q%2*40564

```

Try it online!

# Answer
> 6 votes
# 05AB1E, ~~34~~ ~~23~~ 22 bytes

```
₁‰`Ðr^‚₁β2‰`Ž$×*Žâ∊α^^

```

-12 bytes thanks to *@CommandMaster*

Try it online or verify all test cases.

**Explanation:**

05AB1E lacks bitshift builtins, so instead we'll use modulo/multiply where applicable.

```
₁‰           # Divmod the (implicit) input-integer by 256
             # (since the input is guaranteed to be a 16-bit integer)
  `          # Pop and push both the quotient and remainder to the stack
   Ð         # Triplicate the remainder
    r        # Reverse the stack from q,r,r,r to r,r,r,q
     ^       # Bitwise-XOR the remainder and quotient together
‚            # Pair the r and r^q together
 ₁β          # Convert it from a base-256 list to a (base-10) integer
2‰           # Divmod it by 2
  `          # Pop and push quotient and remainder separated to the stack
   Ž$×       # Push compressed integer 25204
      *      # Multiply it to the remainder
       Žâ∊   # Push compressed integer 57460
          α  # Take the absolute difference of the two values
           ^ # Bitwise-XOR it to the quotient
^            # Bitwise-XOR it to third remainder-copy that was still on the stack
             # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž$×` is `25204` and `Žâ∊` is `57460`.

# Answer
> 5 votes
# C (gcc), <sup>~~53~~</sup> 52 bytes

```
q;f(n){q=n>>8^(n&=255);n=q/2^n<<7^n^57460-q%2*'bt';}

```

Try it online!

*Saved a byte thanks to ceilingcat!!!*

Port of Arnauld's JavaScript answer.

# Answer
> 3 votes
# Retina 0.8.2, 173 bytes

```
.+
16$*0$&$*
+`(1+)\1
$+0
01
1
.*(.{8})(.{8})
$2$1
(?<=1.{7})(1|(0))
$#2
1$
11001111001110100
^((.{8}).{7}).
$+0${1}1110000001110100
+`1(.{15})(1|(0))
0$1$#3
1
01
+`10
011
1

```

Try it online! Link includes less slow test cases. Explanation:

```
.+
16$*0$&$*

```

Convert to unary, but also prefix 16 `0`s, so the binary value below has at least 16 digits.

```
+`(1+)\1
$+0
01
1

```

Convert to binary.

```
.*(.{8})(.{8})
$2$1

```

Swap the bottom eight bits with the next eight, and discard any remaining zeros.

```
(?<=1.{7})(1|(0))
$#2

```

XOR the top eight bits into the bottom eight bits, i.e. toggle any digit seven digits after a `1`.

```
1$
11001111001110100

```

Append `0x8180 ^ 0x1FF4` if the value ends in a `1`.

```
^((.{8}).{7}).
$+0${1}1110000001110100

```

Replace the value with two copies shifted eight bits and one bit right and also append `0xFF80 ^ 0x1FF4`.

```
+`1(.{15})(1|(0))
0$1$#3

```

(Destructively) XOR all of the values together.

```
1
01
+`10
011
1

```

Convert to decimal. Note that this takes `O(n²)` time, which makes the test cases take up to 25 seconds each on TIO, so I've also written a Retina 1 port but using fast binary to decimal conversion: Try it online! Link includes test cases.

# Answer
> 3 votes
# MIPS III, ~~68~~ ~~60~~ ~~52~~ 48 bytes

```
308800ff
00044a02
01285026
00085a00
016a5825
000b1042
00481026
316c0001
15800000
38429e74
03e00008
38427e00

```

Source:

```
rng:                                    # a0 = seed
        andi    $t0, $a0, 0xFF          # s_lo
        srl     $t1, $a0, 8             # s_hi
        xor     $t2, $t1, $t0           # s_lo ^ s_hi
        sll     $t3, $t0, 8             # s_lo << 8
        or      $t3, $t3, $t2           # c = (s_lo << 8) | (s_lo ^ s_hi)

        srl     $v0, $t3, 1             # c / 2
        xor     $v0, $v0, $t0           # xor with s_lo

        andi    $t4, $t3, 1             # c odd
        bne     $t4,  $0, exit
exit:   xori    $v0, $v0, 0x9E74        # xor twice if branch taken, eff. nop
                                        # 7E00 ^ E074
        jr      $ra
        xori    $v0, $v0, 0x7E00

```

Well I had to, didn't I? Even if MIPS is a terrible golfing language as far as assembly languages go, due to every single instruction being 4 bytes (wasting instruction encoding bits) and requiring unintuitive instruction re-ordering to not waste branch delay slots. It still beats out whatever actually was on the game ROM since I didn't have all of the mentioned Nintendo's extraneous / unreachable code.

-8 bytes from combining left and right shifts as in the math notation in the question. Also rewrote the comments to be much easier to follow.

-8 bytes from being smarter about `c` calculation thanks to m90.

-4 bytes from rearranging instructions to avoid a `nop` in the return jump branch delay slot. Here the control flow is weird: the branch (with offset 0) to a label at the delay slot causes the xor instruction to be executed twice if the branch is taken, once as part of the delay slot and again after branching, acting effectively as a no-op. AFAICT this is the intended behavior (at least supported by the MARS simulator).

# Answer
> 1 votes
## Batch, 58 bytes

```
@cmd/cset/a"q=%1>>8^(n=%1&255),q/2^n<<7^n^57460^q%%2*40564

```

Another port of @Arnauld's JavaScript answer.

# Answer
> 1 votes
# Python, 55 bytes

```
lambda n:(q:=n>>8^(n:=n&255))//2^n<<7^n^57460^q%2*40564
```

Attempt This Online!

I'm late to the party, but yet another port of @Arnauld's JavaScript answer.

# Answer
> 1 votes
# SM83/Z80, 24 bytes

Input in `bc`, output in `bc`.

```
79 A8 41 CB 19 1F 38 08
EE 74 F5 80 EE 9E 4F F1
A8 41 4F 78 EE 7E 47 C9

```

Explanation and disassembly:
First, here's the pseudocode I used for this.

```
s0 = r << 8;
s0 ^= r;
r = swab(s0);           // A
s1 = r & 1;
r >>= 1;                // B
if(!$1) r ^= 0x9E74;
r ^= s0 & 0xff          // C
r ^= 0x7E00             // D

```

Now the assembly:

```
sm64rng:
;; r starts in bc
    ld a,c          ;; 79
    xor b           ;; A8
    ld b,c          ;; 41
;; now s0 in ab, r in ca, after line A.
    rr c            ;; CB 19
    rra             ;; 1F
;; now s0 & 0xff in b, r in ca, s1 in cf, after line B.
    jr c, ifodd     ;; 38 08
    xor $74         ;; EE 74
    push af         ;; F5
    ld a,c          ;; 79
    xor $9E         ;; EE 9E
    ld c,a          ;; 4F
    pop af          ;; F1
ifodd:
;; now s0 & 0xff in b, r in ca, before line C.
    xor b           ;; A8
;; now after line C.
    ld b,c          ;; 41
    ld c,a          ;; 4F
    ld a,b          ;; 78
;; r now in ac
    xor $7E         ;; EE 7E
;; now after line D
    ld b,a          ;; 47
;; r now in bc
    ret             ;; C9

```

Note that this doesn't work on Z80studio, because the bit instructions are currently badly broken and `rr c` doesn't work properly, because it messes up the flags (and taken jumps go to the place two bytes before they should). But after some fixing of the Javascript, it can be tested!

# Answer
> 1 votes
# Rust, ~~141~~ ~~90~~ ~~79~~ ~~75~~ 74 bytes

Saved 67 bytes thanks to @ceilingcat

---

Golfed version. Try it online!

```
|mut n:u16|->u16{n^=n%256<<8;n=n%256*2^n.swap_bytes();n/2^57460-n%2*25204}

```

Ungolfed version. Try it online!

```
fn rng(mut input: u16) -> u16 {
    let mut s0: u16;
    let s1: u16;

    s0 = (input & 0xFF) << 8; // shift low byte to high
    s0 ^= input;
    input = (s0 & 0xFF) << 8 | (s0 & 0xFF00) >> 8; // swap 8-bit halves
    s0 = (s0 & 0xFF) << 1 ^ input;
    s1 = s0 >> 1 ^ 0xFF80;
    if s0 & 1 != 0 {  // depending on s0 odd or even, XOR with one of 2 constants
        input = s1 ^ 0x8180;
    } else {
        input = s1 ^ 0x1FF4;
    }
    input
}

fn main(){
    // Example usage with given inputs
    let inputs1 = [12567, 60400, 1789, 0, 57460, 55882, 50550];
    for &input in &inputs1 {
        println!("{} -> {}", input, rng(input));
    }
    println!();
    let inputs2 = [64917, 43605, 21674, 46497, 45151];
    for &input in &inputs2 {
        println!("{} -> {}", input, rng(input));
    }
    println!();
    // Special case to check bi-directional mapping
    println!("22026 <-> {}", rng(22026));
    println!("58704 <-> {}", rng(58704));
}

```

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

It's a direct port of Arnauld's Javascript answer.

```
$_=($t=$_>>8^($_&=255))/2^$_<<7^$_^57460^$t%2*40564

```

Try it online!

---
Tags: code-golf, random, game
---