title: Tell me my screen resolution!

text:
# Question
Title: Tell me my screen resolution!
Output the device's screen resolution in the **specific** format of `[width]x[height]`(without the brackets). For example, an output could be `1440x900`.

Here's an online tester that you can use to check your own screen resolution.

# Answer
> 38 votes
# JavaScript (ES6), 32 bytes

```
(_=screen)=>_.width+"x"+_.height

```

Outputs as function `return`. Add `f=` at the beginning and invoke like `f()`. Uses parameter-initializing to initialize the parameter `_` to `screen` object. The rest is self-explanatory.

```
f=(_=screen)=>_.width+"x"+_.height
console.log(f())
```

**Note:** Passing an argument to this function will cause it to fail.

---

# JavaScript (Previous Solution), 35 bytes

```
with(screen)alert(width+"x"+height)
```

Never thought I will one day use `with`! I don't think this can be golfed further.

# Answer
> 34 votes
# TI-BASIC, ~~30~~ ~~32~~ 29 bytes (non-competing?)

\*sigh\* TI-BASIC takes an extra byte for every lowercase letter.

+2 thanks to @Timtech

-3 thanks to @Timtech

```
:If ΔX>.1
:Then
:Disp "96x64
:Else
:Disp "320x240

```

This only works because TI-BASIC can only be run on calculators with two different screen resolutions: 96 by 64 and 320 by 240. I just test to see which screen I have by setting the Zoom to something that is different depending on screen resolution then outputting the correct resolution.

I'm marking this as non-competing for now, since it is hard coded.

# Answer
> 20 votes
# JavaScript (ES6), 32 bytes

```
_=>(s=screen).width+'x'+s.height

```

```
console.log((_=>(s=screen).width+'x'+s.height)())
```

# Answer
> 11 votes
# macOS, bash, awk, ~~grep, tr, 51~~ 52 bytes

```
/*/*/sy*r SPDisplaysDataType|awk '/so/{print$2$3$4}'

```

Runs `system_profiler`, gets the `SPDisplaysDataType` information, searches for the first `so` in `Resolution`, and prints the screen resolution. For multiple screens, this prints all resolutions.

---

The prior, malcompliant variant:

```
/*/*/sy*r SPDisplaysDataType|grep so|tr -d 'R :a-w'

```

# Answer
> 9 votes
# Javascript, 36 bytes

```
s=screen;alert(s.width+"x"+s.height)
```

# Answer
> 9 votes
# Processing 3, 37 bytes

```
fullScreen();print(width+"x"+height);

```

`fullScreen()` causes the app to launch with the maximum dimensions - the display resolution. One byte less than the obvious

```
print(displayWidth+"x"+displayHeight);

```

# Answer
> 9 votes
# AutoHotKey, 34 bytes

```
SysGet,w,0
SysGet,h,1
Send,%w%x%h%

```

Save this in a file with extension .AHK and run it from a command prompt

# Answer
> 7 votes
# PowerShell, ~~67~~ ~~60~~ 55 Bytes

-7 thanks to Martin Ender

-5 (actually 12!) from Leaky Nun , Regex wizardry is beyond me.

This is long but not longer than the horrendous `System.Windows.Forms.SystemInformation.PrimaryMonitorSize` solution

```
(gwmi win32_videocontroller|% v*n)-replace" |x \d+\D+$"

```

first we `Get-WmiObject`(`gwmi`) to retrieve the `Win32_VideoController` object, which contains a member named `VideoModeDescription`, which is a string in the format of `1920 x 1080 x 4294967296 colors`, then I run a regex replace to get correct format.

```
PS H:\> (gwmi win32_videocontroller|% v*n)-replace" |x \d+\D+$"
1920x1080

```

# Answer
> 7 votes
# C (Windows), ~~79~~ ~~78~~ 77 bytes

*Thanks to @Johan du Toit for saving a byte!*

```
#import<windows.h>
#define G GetSystemMetrics
f(){printf("%dx%d",G(0),G(1));}

```

# Answer
> 6 votes
# Bash + xrandr, 44 characters

```
read -aa<<<`xrandr`
echo ${a[7]}x${a[9]::-1}

```

`xrandr` belongs to the X server, on Ubuntu is provided by *x11-xserver-utils* package.

Sample run:

```
bash-4.3$ read -aa<<<`xrandr`;echo ${a[7]}x${a[9]::-1}
1920x1080

```

## xrandr + grep + util-linux, 30 characters

```
xrandr|grep -oP '\d+x\d+'|line

```

Thanks to:

Sample run:

```
bash-4.3$ xrandr|grep -oP '\d+x\d+'|line
1920x1080

```

# Answer
> 6 votes
# Java 7, ~~123~~ 114 bytes

```
String f(){java.awt.Dimension s=java.awt.Toolkit.getDefaultToolkit().getScreenSize();return s.width+"x"+s.height;}

```

This method will not work in a headless installation of Java (like on TIO) because it uses the awt libraries. Under the hood, calling `getScreenSize` uses the Java Native Interface to call out (typically into a C library) for the screen width and screen height.

-9 bytes thanks to Olivier Grégoire for reminding me that I can return the string instead of printing it.

# Answer
> 6 votes
# C#, ~~101~~ ~~95~~ 89 bytes

```
_=>{var s=System.Windows.Forms.Screen.PrimaryScreen.Bounds;return s.Width+"x"+s.Height;};

```

-6 bytes thanks to *@TheLethalCoder* by reminding me OP didn't mention about printing, so returning a string is also fine. And an additional -6 bytes by changing it to a lambda.

# Answer
> 6 votes
## Mathematica, 51 bytes

```
SystemInformation[][[1,5,2,1,2,1,2,2,;;,2]]~Infix~x

```

This may not work for you depending on what devices you have connected (I don't know). This should always work (assuming you have at least one screen hooked up):

```
Infix[Last/@("FullScreenArea"/.SystemInformation["Devices","ScreenInformation"][[1]]),x]

```

## Explanation

`SystemInformation[]` returns an expression of the form

```
SystemInformationData[{
  "Kernel" -> {__},
  "FrontEnd" -> {__},
  "Links" -> {__},
  "Parallel" -> {__},
  "Devices" -> {__},
  "Network" -> {__},
}]

```

We are interested in `"Devices"`, which can be accessed directly as `SystemInformation["Devices"]` or as `SystemInformation[][[1,5,2]]`. The result will be a list of the form

```
{
  "ScreenInformation" -> {__},
  "GraphicsDevices" -> {__},
  "ControllerDevices" -> {__}
}

```

We want `"ScreenInformation"`, which can be accessed either as `SystemInformation["Devices","ScreenInformation"]` or more succinctly as `SystemInformation[][[1,5,2,1,2]]`. The result will be of the form

```
{
  {
  "ScreenArea" -> {__},
  "FullScreenArea" -> {{0,w_},{0,h_}},
  "BitDepth" -> _,
  "Resolution" -> _
  },
  ___
}

```

The length of the list will be the number of screens you have connected. The first screen is `SystemInformation[][[1,5,2,1,2,1]]` and the width and height can be extracted as `SystemInformation[][[1,5,2,1,2,1,2,2,;;,2]]` Then we just insert an `Infix` `x` for the output format.

# Answer
> 5 votes
# Octave, 41 bytes

*Thanks to @Arjun and @StephenS for corrections.*

```
fprintf('%ix%i',get(0,'ScreenSize')(3:4))

```

`0` is a handle to the root graphics object. Its property `'ScreenSize'` contains the coordinates of the screen in pixels. The third and fourth entries give the desired information.

# Answer
> 5 votes
# APL (Dyalog), 23 bytes

```
' '⎕R'x'⍕⌽⊃⎕WG'DevCaps'

```

`⎕WG'DevCaps'`**W**indow **G**et **Dev**ice **Cap**abilitie**s**

pick the first property (height, width)

reverse

format as text

`' '⎕R'x'`**R**eplace spaces with "x"s

# Answer
> 5 votes
# Python 2, 73 bytes

```
from ctypes import*
u=windll.user32.GetSystemMetrics;
print u(0),'x',u(1)

```

# Answer
> 4 votes
## Japt, 24 bytes

```
Ox`ØP(s×Çn)±d+"x"+ight

```

Test it online!

The compressed string represents `with(screen)width+"x"+height`. `Ox` evaluates this as JavaScript, and the result is implicitly printed.

# Answer
> 4 votes
# C (SDL2 library) ~~113~~ ~~88~~ 84

(-4 chars due to @AppleShell 's help)

Yes. it compiles.

```
m[3];main(){SDL_Init(32);SDL_GetDesktopDisplayMode(0,m);printf("%dx%d",m[1],m[2]);}

```

Run with : `gcc snippet.c -lSDL2 && ./a.out`

# Answer
> 4 votes
`xrandr` \+ awk, 25 bytes

```
xrandr|awk /\*/{print\$1}

```

---

# Answer
> 4 votes
# Python 2, ~~61~~ 49 bytes

Thanks @Jonathan-allan, @felipe-nardi-batista

```
from Tkinter import*
print'%sx%s'%Tk().maxsize()

```

For single display setups, this matches the output from the site. This gives entire resolution for multiple displays.

# Answer
> 4 votes
# ZX Spectrum Basic, 10 bytes

just for completeness:

```
PRINT "256x192"

```

outputs `256x192`. The Spectrum has a fixed hardwired screen resolution.

# Answer
> 3 votes
## bash + xdpyinfo  ~~42~~  31 bytes

```
xdpyinfo|grep dim|cut -d' ' -f7

```

From man page:

```
xdpyinfo - is  a utility for displaying information about an X server.

```

@Floris @manatwork Thanks for saving a few bytes!

# Answer
> 2 votes
# Processing, 51 bytes

```
void setup(){fullScreen();print(width+"x"+height);}

```

This outputs in this format: `width height`. Also, the program creates a window that is the size of the screen you are using (because every Processing program creates a window by default) and this program just outputs the height and the width of this window/sketch.

# Answer
> 2 votes
### `xdpyinfo` \+ `awk`, 28 bytes

```
$ xdpyinfo|awk /dim/{print\$2}
3360x1050

```

Tested on Cygwin with dual heads.

# Answer
> 2 votes
# Racket, 73 bytes

```
#!racket/gui
(let-values([(x y)(get-display-size #t)])(printf"~ax~a"x y))

```

Just discovered the (discouraged) shorthand for `#lang`. Saves a few bytes! Documentation for `get-display-size`.

# Answer
> 1 votes
# Tcl/Tk, 40

```
puts [winfo screenw .]x[winfo screenh .]

```

# Answer
> 1 votes
# Batch, ~~218 208~~ 206 bytes

I can't golf....

```
@for /f %%# in ('"@wmic path Win32_VideoController get CurrentHorizontalResolution,CurrentVerticalResolution /format:value"')do @set %%#>nul
@echo %CurrentHorizontalResolution%x%CurrentVerticalResolution%

```

# Answer
> 1 votes
## Ruby + xrandr, 37 bytes

```
puts `xrandr`.split[7..9].join[0..-2]

```

Alternate solution (52 bytes):

```
puts `xrandr`.match(/t (\d+) (x) (\d+),/)[1..3].join

```

# Answer
> 1 votes
## Lithp, 116 bytes

```
((import html-toolkit)
(htmlOnLoad #::((var S(index(getWindow)screen))
(print(+(index S width)"x"(index S height))))))

```

(Line breaks added for readability)

Try it online!

Finally, my html-toolkit module gets some use! Only works in the Try it Online link, will not work from command line.

A few bytes could be saved if `1024 x 768` could be valid output. We just use `(+ .. "x" .. )` to avoid `print`'s implicit spacing.

# Answer
> 1 votes
# Lua (löve framework),116 bytes

```
f,g=love.window.setFullscreen,love.graphics function love.draw()f(1)w,h=g.getDimensions()f(0>1)g.print(w.."x"..h)end

```

The programm changes first to fullscreen then it gets the width and height and prints it then :)

# Answer
> 1 votes
### xrandr and sh, 23 bytes

```
$ set `xrandr`;echo $6x$8
3360x1050

```

Tested on a CentOS 5 box with display redirected to a Cygwin machine with two monitors. Here the full `xrandr` output is

```
$ xrandr
 SZ:    Pixels          Physical       Refresh
*0   3360 x 1050   ( 889mm x 278mm )  *0
Current rotation - normal
Current reflection - none
Rotations possible - normal
Reflections possible - none

```

# Answer
> 1 votes
## Bash + xdotool + tr, 35 bytes

*-1 thanks to @manatwork*

```
xdotool getdisplaygeometry|tr \  x

```

There are two spaces after the `\`

Gets geometry, then uses `tr` to replace spaces with `x`

# Answer
> 1 votes
# Python 3, 54 bytes

# Python 2, 52 51 bytes

```
from PIL.ImageGrab import*;print'%dx%d'%grab().size

```

Saved 2 bytes by executing in Python 2

Saved 1 byte by changing import

# Answer
> 1 votes
# Javascript, 42 bytes

```
console.log((k=screen).width+'x'+k.height)

```

# Answer
> 1 votes
# Red, 26 Bytes

```
system/view/screens/1/size

```

Outputs for example:

```
1920x1080

```

The code is pretty self explanatory. The `1` refers to the first screen

# Answer
> 1 votes
# Batch, 128 125 124 123 bytes

```
@for /f "tokens=1,2delims=x " %%A in ('wmic path Win32_VideoController get VideoModeDescription^|find "l"')do @echo %%Ax%%B

```

Basically the same thing as SteveFest's answer, except I grab a slightly shorter chunk of Wim32\_VideoController and then I use something vaguely resembling regex to get the one line that contains the data that I want.

I have no idea why the `wmic` string needs to be inside of double quotes to work I needed the quotes so that I didn't need to escape the pipe, but `^` is shorter than `""`, and I can't believe that I can't shorten the wmic command at all.

## How It Works

Ordinarily, `wmic path Win32_VideoController get VideoModeDescription` will display something like this:

```
VideoModeDescription
3440 x 1440 x 4294967296 colors

```

I can use `findstr`'s super rudimentary attempt at regex `find` to find the letter "l," which only matches the line with the word "colors." From there, that line is delimited on spaces and the letter "x." `%%A` contains the first token and `%%B` contains the second token. After that, I just display the values.

# Answer
> 0 votes
# Python 2, 60 bytes

```
from win32api import*
u=GetSystemMetrics
print u(0),'x',u(1)

```

# Answer
> 0 votes
# C#, 90 Bytes

```
()=>{var b=System.Windows.Forms.Screen.PrimaryScreen.Bounds;return b.Width+"x"+b.Height;};

```

This actually is quite a similiar answer to that one, which already exists, however, I'd like to add a few things. This solution acutally needs a reference to *System.Windows.Forms* and one to *System.Drawing*. Those references are not normally added for a console application, so I'm not sure wether it's valid. Therefore I wrote a solution **without references**, however this has **580 287 Bytes**:

```
using System;using System.Runtime.InteropServices;class P{static void Main()=>Console.Write(G().Item1+"x"+G().Item2);static(int,int)G()=>(GetSystemMetrics(0),GetSystemMetrics(1));[DllImport("User32.dll",ExactSpelling=true,CharSet=CharSet.Auto)]static extern int GetSystemMetrics(int n);}

```

Here's the solution with line breaks:

```
using System;
using System.Runtime.InteropServices;

class P
{
    static void Main() => Console.Write(G().Item1 + "x" + G().Item2);
    static (int, int) G() => (GetSystemMetrics(0), GetSystemMetrics(1));

    [DllImport("User32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
    static extern int GetSystemMetrics(int n);
}

```

This solution was created with the huge help of AdamSchiavone on Stackoverflow.

I also wrote a **C# Interactive** programm with **123 Bytes**, which automatically adds the references, so it can be executed on every machine without problems and without having the reference problems:

```
#r "System.Windows.Forms"
#r "System.Drawing"
var b=System.Windows.Forms.Screen.PrimaryScreen.Bounds;b.Width+"x"+b.Height

```

This basically is the same as the first one, but it adds the reference automatically and as it is executed in the interactive, you don't need the return statement, you can simply leave away the semicolon.

# Answer
> 0 votes
## C#, 89 bytes

```
_=>{var s=System.Windows.Forms.Screen.PrimaryScreen.Bounds;return s.Width+"x"+s.Height;};

```

# Answer
> 0 votes
# PHP + GTK 2.0, 69 bytes

This whole answer was written based on http://php-gtk.eu/en/code-hints/grabbing-a-screenshot-with-gdk

```
<?list($W,$H)=Gdk::get_default_root_window()->get_size();echo$W,x,$H;

```

Basically, fetches the "root" window (entire screen) and gets it's size.

---

Another way (based on http://www.kksou.com/php-gtk2/sample-codes/get-the-size-of-display-screen.php):

```
<?$w=(new GtkWindow())->get_screen();echo$w->get_width(),x,$w->get_height();

```

Gets the screen where the window was created, displaying it's dimentions.

# Answer
> 0 votes
# Javascript, 46 bytes

```
var s=screen;console.log(s.width+'x'+s.height)

```

I wanted to write it in the comment but I don't have reputation yet. Can someone explain to me why other solutions don't count bytes for `console.log()`? If they were counted then this solution would be the shortest.

# Answer
> 0 votes
## MATLAB, 42 byte

```
a=get(0,'ScreenS');fprintf('%dx%d',a(3:4))

```

Uses property shortening. Other than that, this is a nice showcase of the inflexibility of MATLAB indexing, requiring a temporary variable `a`. `fprintf` prints to `stdout` by default.

# Answer
> 0 votes
# Clojure, 86 bytes

Shameless port of this Java answer

```
(#(str(.width %1)"x"(.height %1))(.getScreenSize(java.awt.Toolkit/getDefaultToolkit)))

```

# Answer
> 0 votes
# 8th, 32 bytes

```
0 hw:displaysize? swap . "x" . .

```

Returns the device's screen resolution of the first display (0) in pixels in the required format.

Output:

```
1536x864

```

# Answer
> 0 votes
# VBA (32-Bit), 110 Bytes

Locally declared windows function and anonymous VBE immediate window function that takes no input and outputs to the VBE Immediate window.

<sub>*Note: The below may be made into a 64-bit compatible function by the addition of `PtrSafe`  following `Declare`* </sub>

```
Declare Function GetSystemMetrics Lib"user32.dll"(ByVal i&)As Long

```

```
?GetSystemMetrics(0)&"x"&GetSystemMetrics(1)

```

# Answer
> 0 votes
# VBScript, 201 bytes

```
For Each x in CreateObject("WbemScripting.SWbemLocator").ConnectServer(".","root\cimv2").ExecQuery("SELECT * FROM WIN32_VIDEOCONTROLLER")
a=Split(x.VideoModeDescription," x ")
msgbox a(0)&"x"&a(1)
Next

```

Connection to Local WMI is eating up all the bytes.....

# Answer
> 0 votes
# VB6, 57 bytes

```
Sub a:Msgbox Screen.Width/15&"x"&Screen.Height/15:End Sub

```

# Answer
> -1 votes
# Bash, 21 bytes

```
tr , x</*/*/*/fb0/v*

```

If the device has frame buffer you can query `/sys/class/graphics/fb0/virtual_size` to get resolution. Width and Height are delimited by `,` so tr translates to `x`. Path to the file is shortened by using * to the point there are no ambiguities.

---
Tags: code-golf
---


title: Which answer did this user write?

text:
# Question
Title: Which answer did this user write?
*EDIT (Jan 19, 2022, 18:00 UTC): This challenge is now over. The winner is Citty with this Pyth answer. Congratulations!*

---

This is an challenge where each answer must take an integer \\$N\\$ as input and return the **1-indexed ID** of the answer which was written by the user whose ID is \\$N\\$.

You may want to sort by oldest to get the answers in the logical order.

## Rules

1. I will post the first answer.
2. You are only allowed to post one answer, so that a user ID is linked to one and only one answer ID.
3. You are only supposed to support user IDs that were used in the previous answers and your own user ID. (So your code may return anything or crash when given an unknown user ID.)
4. **The maximum code size is set to 50 bytes**. So the challenge will end when nobody is able to add a new ID without exceeding this size.
5. You may use any language, no matter which ones were used before. It is recommended to use verbose languages early in the chain, while they still have a chance to compete.
6. The last valid answer in the chain on January 19, 2022 at 18:00 UTC wins the challenge.

Please include in your post the list of ID pairs, updated with your new entry:

```
[your_user_ID] -> [your_answer_ID]

```

Also make sure to include the ID of your answer in the header.

## Examples

The first answer is written by user **Arnauld (58563)**:

### 1. JavaScript (ES6), 4 bytes

```
_=>1

```

Try it online!

Updated list:

```
58563 -> 1

```

This code returns **1** when given **58563** (my user ID) ... or any other input. That's fine because **1** is the only possible output at this point (see rule #3).

The second answer is written by user **JohnDoe (123456)** (who actually doesn't exist yet):

### 2. Python 2, 14 bytes

```
lambda n:2-n%2

```

Try it online!

Updated list:

```
58563 -> 1
123456 -> 2

```

This code returns **1** when given **58563** or **2** when given **123456**.

# Answer
# 7. Julia, 17 bytes

works due to `Int64` overflowing to negative numbers

```
x->(x-8479)^6%5+5

```

Try it online!

**Updated list:**

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7

```

**I found those numbers by guessing and brute-forcing :**

```
for i in Iterators.product(-9999:9999,1:20,1:20)
    d = diff(((L.+i[1]) .^ i[3]) .% i[2])
    if all(==(-1), d) || all(==(1),d)
        println(i)
        println(((L.+i[1]) .^ i[3]) .% i[2])
        break
    end
end

```

Try it online!
> 14 votes

# Answer
# 2. Ruby, 11 bytes

```
->x{1+~x%2}

```

Try it online!

Updated list:

```
58563 -> 1
80214 -> 2

```
> 9 votes

# Answer
# 1. JavaScript (ES6), 4 bytes

```
_=>1

```

Try it online!

Updated list:

```
58563 -> 1

```
> 8 votes

# Answer
# 6. Zsh, <sup>~~26~~</sup> 25 bytes

```
a=80596
<<<$a[(i)${1[2]}]

```

Try it online!

Boring.

*-1 by @GammaFunction*

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6

```
> 8 votes

# Answer
# 8. , 46 bytes

Last time this works, here to grab the boring answer!

```
1+58563 80214 95792 89930 86147 97857 98541&i.

```

`95594` doesn't need to be included as J's index-of-operator `i.` returns the length of the array in the case the item was not found. But as it is 0-based, the index gets incremented `1+`.

Try it online!

Update list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8

```
> 8 votes

# Answer
# 9. Perl 5 `-p`, ~~46~~, 37 bytes

```
$_=(a74a298635=~/./g)[$_%26%20%12]||1

```

Try it online!

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9

```

Explanation:

```
$_=$_%26%20%12 gives
58563 -> 11
80214 -> 4
95792 -> 8
89930 -> 2
86147 -> 9
97857 -> 7
98541 -> 1
95594 -> 6
70745 -> 5
(a74a298635=~/./g) because shorter than (a,7,4,a,2,9,8,6,3,5)

```
> 8 votes

# Answer
# 13. Python 3, 45 bytes

```
lambda n:ord('ehlkacfbdgimj'[n%209%80%13])-96

```

Try it online!

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11
44718 -> 12
 9481 -> 13

```
> 8 votes

# Answer
# 15. 05AB1E, 42 bytes

This is based on the Chinese remainder theorem. Since all divisors need to be pairwise coprime, we use the `n`th prime for each user id `n`.

```
•3hy₁Ω=”Ó6™≠ò“êS’>₄?Θ¢9?Âγ”J4 %œ~ª‰fÃα•IØ%

```

Try it online!

`•3hy...fÃα•` is the large compressed integer `1369130535064223821413376960561972089702936948491908270885271972462351716275011314738309`.
`I` pushes the input, `Ø` takes the n-th prime and `%` takes the large compressed integer modulo the prime number.

The big constant is generated with the ChineseRemainder builtin from the Wolfram Language: Try it online!

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11
44718 -> 12
 9481 -> 13
78123 -> 14
64121 -> 15

```

---

By using the closest prime to `n/349` instead of the `n`th prime this can be golfed to 24 bytes:

```
•1RMζ)šÙ&KxγŸÏäí•IƵù/Ån%

```

Try it online!

```
•1R...äí•         # compressed integer 5437583563235532232480395276083021
         I        # push the input
          Ƶù/     # divide by 349
             Ån   # find the nearest prime
               %  # modulo the large integer with the prime

```
> 8 votes

# Answer
# 20. Charcoal, 30 bytes

```
Ｉ⁺²⌕⪪”)¶q⁹1＆¡⍘DλＫ⟦l∧NＨz¿”²…⮌Ｓ²

```

Try it online! Link is to verbose version of code. Works by taking the last two digits of the user ID and looking it up in a table generated by splitting a compressed string into pairs of characters. (Taking the first two digits doesn't work because there are several repeats.) A few variants are possible by spending an extra byte or two on the table which are offset by the saving from not having to offset the resulting index. Unfortunately there are overlaps between adjacent user IDs which means that the string has to be split into pairs of characters to find the index accurately, although one byte of this is offset by not having to halve the resulting index. Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11
44718 -> 12
 9481 -> 13
78123 -> 14
64121 -> 15
41565 -> 16
52210 -> 17
91569 -> 18
 3852 -> 19
17602 -> 20

```
> 8 votes

# Answer
# 3. APL (Dyalog Unicode), 7 bytes

```
4|∘⍎3⊃⍕

```

Try it online!

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3

```

Explanation:

```
4|∘⍎3⊃⍕
       ⍕  ⍝ Convert to string
     3⊃   ⍝ Pick the third digit (5, 2, or 7)
   ⍎      ⍝ Execute (make the digit a number again)
4|        ⍝ Mod 4

```
> 7 votes

# Answer
# 12. C (gcc), 50 bytes

```
int f(int n){return"DJHABILFCGKE"[n%60%50%12]-64;}

```

Try it online!

This code could be golfable. But this question is not taged . So let's leave it warning free.

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11
44718 -> 12

```
> 7 votes

# Answer
# 17. MathGolf, ~~41~~ 40 bytes

```
☼+░╞╪2<W48R087`9H4957V6984♂Y☻5405]y2/├=)

```

Try it online.

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11
44718 -> 12
 9481 -> 13
78123 -> 14
64121 -> 15
41565 -> 16
52210 -> 17

```

**Explanation:**

```
☼+           # Add 100000 to the (implicit) input-integer
  ░          # Convert it to a string
   ╞         # Remove the first digit (the 1)
             # (the `☼+░╞` is used to convert the input 9481 to "09481",
             #  and at the same time convert any other input-integer to a string)
╪            # Rotate it once towards the right
 2<          # Leave only the first two characters
   W48R087`9H4957V6984♂Y☻5405
             # Push the following integers to the stack
             # (where ` duplicates the top two items, thus 8,7):
             #  35,4,8,29,0,8,7,8,7,9,19,4,9,5,7,34,6,9,8,4,10,37,16,5,4,0,5
    ]y       # Wrap the stack in a list, and join it together
      2/     # Split it into parts of size 2
        ├    # Pop the left item from the list, and push it to the stack
             # (which is the value we calculated at first)
         =   # Get its 0-based index in the list
          )  # And increase it by 1 to make it a 1-based index
             # (after which the entire stack is output implicitly as result)

```
> 7 votes

# Answer
# 21. Pyth, 49 50 bytes

`(answer ID & 753) % 38` happens to be unique for every answer so I just use that to make a lookup table.

```
C@" \r
          "%.&753Q38

```

The string in python repr format: `' \r\x14\x01\x02\t\x04\x06 \n \x05\x0b\x0f\x13 \x08 \x10 \x12\x0c \x03 \x11 \x0e \x07'`

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11
44718 -> 12
 9481 -> 13
78123 -> 14
64121 -> 15
41565 -> 16
52210 -> 17
91569 -> 18
 3852 -> 19
17602 -> 20
75429 -> 21

```

+1 byte because Python doesn't like carriage returns on their own apparently

Try it online!
> 7 votes

# Answer
# 4. C# (.NET Core), 16 bytes

```
n=>2-n%2+n%100%7

```

Try it online!

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4

```

Lucky coincidence that

* All IDs except the first are even
* Last 2 digits of the first 2 IDs are divisible by 7
* Last 2 digits of the second 2 IDs are 1 and 2 mod 7 respectively
> 6 votes

# Answer
# 5. Zsh, 25 bytes

```
<<<$[$1&7?(4+${1:4})%6:3]

```

Try it online!

`(4 + ${1:4}) % 6` works for every ID but 95792. But, 95792 is the only ID divisible by 8, so a ternary with `$1 % 8` as the condition works.

```
58563  ->  3 ? (4 + 3) % 6 : 3  ->  7 % 6  ->  1
80214  ->  6 ? (4 + 4) % 6 : 3  ->  8 % 6  ->  2
95792  ->  0 ? (4 + 2) % 6 : 3  ->             3
89930  ->  2 ? (4 + 0) % 6 : 3  ->  4 % 6  ->  4
86147  ->  3 ? (4 + 7) % 6 : 3  -> 11 % 6  ->  5

```

The more boring **24 byte** answer, based off of @pxeger's

```
a=8059
<<<$a[(i)${1[2]}]

```
> 6 votes

# Answer
# 18. 05AB1E, 45 bytes

```
•1ααāš®‚wA%|ʒη¦%áYζ”€…FKΘćRÉ±nG’*AÂÉζ•5ôíÌskÌ

```

Try it online!

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11
44718 -> 12
 9481 -> 13
78123 -> 14
64121 -> 15
41565 -> 16
52210 -> 17
91569 -> 18

```

The compressed number is each user ID minus 2, reversed, and joined together (except `9481` which is changed into `97490`, and `58563` which is not included).  splits it, `εR}` reverses it, `sk` returns the index of the input in the list, and `Ì` adds 2.
> 6 votes

# Answer
# 14. Stax, 48 bytes

```
"&,R>&N_QbmO.%:VUVh5m@x~|LVju(bWJij<$"%98542|EI^

```

Run and debug it

You thought the time for trivial solutions was over? Fool!

Well, maybe not entirely trivial. But the nontrivial part was generated by Stax's array literal generator. The only thing I added is the `I^`, which means "find the index of the input number in the array and increment it".

The code could be packed, but this is not .

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11
44718 -> 12
 9481 -> 13
78123 -> 14

```
> 5 votes

# Answer
# 16. C# (.NET Core), 47 bytes

Not creative... just a basic mapping. Constants came from experimentation

```
x=>" +$Q2('%OINFA;4@0".IndexOf((char)(x%49+35))

```

Try it online!

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11
44718 -> 12
 9481 -> 13
78123 -> 14
64121 -> 15
41565 -> 16

```
> 5 votes

# Answer
# 10. Python 3, 44 bytes

```
lambda x:'973.84.612..5a'[int(x[0]+x[4])%15]

```

Try it online!

Input is taken as a decimal string and returned as a hexadecimal string

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10  (displayed as `a` in this case)

```

## Explanation

Takes the first and last digits, mod 15 and indexes into a string lookup table. This approach won't work for too much longer, but could probably be stretched to 20 or so in a language with more flexible string-\>int conversion, like Javascript, PHP, or Perl.
> 4 votes

# Answer
# 11. 05AB1E, 30 bytes

```
•γ¤š×Pγ…þiðþ–
çô&`)½c©2è•5ôsk>

```

Try it online!

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11

```

---

```
•...•5ôsk>  # trimmed program
        k   # get 0...
         >  # plus 1...
        k   # -based index of...
       s    # implicit input...
        k   # in...
•...•       # 5856380214957928993086147978579854195594707454561394066...
      ô     # split in pieces of...
     5      # literal
            # implicit output

```
> 4 votes

# Answer
# 19. Befunge-93, 45 bytes

```
"0$>K"&\%\%\%\%1g\-.@
/1C274=B8?A5>:/@;3</96

```

Try it online!

Updated list:

```
58563 -> 1
80214 -> 2
95792 -> 3
89930 -> 4
86147 -> 5
97857 -> 6
98541 -> 7
95594 -> 8
70745 -> 9
45613 -> 10
94066 -> 11
44718 -> 12
 9481 -> 13
78123 -> 14
64121 -> 15
41565 -> 16
52210 -> 17
91569 -> 18
 3852 -> 19

```

There's a raw low-ASCII byte (decimal 25) between the `0` and the `$`.

This computes `str[input%75%62%36%25] - '0'`, where `str` is the string on the second line of the program.
> 4 votes

---
Tags: restricted-source, answer-chaining
---


title: What's the odd one out?

text:
# Question
Title: What's the odd one out?
You are to write a program which outputs a single positive integer \\$n\\$. The integer may have leading zeros and whitespace, and/or trailing whitespace.

Then, choose a positive integer \\$m \> 1\\$. When the program is repeated exactly \\$m\\$ times, it should output \\$m \times n\\$ (and only \\$m\times n\\$). When repeated any number of times other than \\$m\\$, it should output \\$n\\$ (and only \\$n\\$).

You may choose the value of \\$m\\$, so long as it is a positive integer greater than 1.

In this context, "repeated \\$m\\$ times" means that the whole program is repeated \\$m\\$ times, rather than each character. For example, repeating `abcde` \\$4\\$ times yields `abcdeabcdeabcdeabcde`.

This is so the shortest code (not repeated \\$m\\$ times) in bytes wins.

---

For example, if your program is `print 5` which outputs 5, and you choose \\$m = 3\\$, then:

* `print 5` should output 5
* `print 5print 5` should output 5
* `print 5print 5print 5` should output 15
* `print 5print 5print 5print 5` should output 5
* `print 5print 5print 5print 5print 5` should output 5
* etc.

# Answer
> 9 votes
# , 16 bytes

```
T=a=1+!T;T=T-1;a

```

Try it online!

Works with \\$n=1\\$ and \\$m=2\\$.

---

Previous version:

## , ~~24~~ ~~23~~ ~~21~~ 19 bytes

-4 bytes thanks to Dominic van Essen

```
T=a=1+0^T^2;T=T-1;a

```

Try it online!

Works with \\$n=1\\$ and \\$m=2\\$. This uses the fact that

\\$0^k = \begin{cases} 1 & \text{ if } k=0\\0& \text { otherwise.}\end{cases}\\$

Therefore, when the code is repeated \\$k\\$ times, we output \\$1+0^{(2-k)^2}\\$, which is worth \\$2\\$ when \\$k=2\\$, and \\$1\\$ otherwise.

# Answer
> 7 votes
# , ~~27~~ ~~20~~ 18 bytes

*Edit: -2 bytes thanks to Robin Ryder, and -2 bytes thanks to pajonk*

```
b=a=3^!(F=F+1)-3;a

```

Try it online!

n=1, m=3 (or trivially for any m up to 9 for same bytes...)

# Answer
> 6 votes
# Python 3, ~~77~~ ~~50~~ ~~46~~ ~~43~~ ~~39~~ 37 bytes

```
input(1+(len([*open(__file__)])==2))

```

Try it online!

Simply counts the number of lines of the code and returns 2 if it is 2 and one otherwise. The `x` is not defined and causes a runtime error immediately after and ends the program.

$$n=1, m=2$$

Thanks to *ChartZ Belatedly* for -27 bytes, *FryAmTheEggman* for -3 bytes, *pxeger* for -4 bytes and *dingledooper* for -2 bytes.

# Answer
> 6 votes
# Bash, 26

n=3, m=2

```
trap echo\ $[++a-2?3:6] 0

```

Try it online!

Try it online!Try it online!

Try it online!Try it online!Try it online!

# Answer
> 5 votes
# PowerShell, 22 bytes, \\$n=1\\$, \\$m=2\\$

```
+!$x+!(++$x-2)-!($x-3)

```

Try it online!

Try it online!Try it online!

Try it online!Try it online!Try it online!

# PowerShell, 39 bytes, \\$n=1\\$, \\$m=2\\$

```
1+((gc $PSCommandPath).Count-eq2);exit

```

Try it online!

# PowerShell 7, 39 bytes, \\$n=1\\$, \\$m=2\\$

```
(gc $PSCommandPath).Count-eq2?2:1;exit

```

# Answer
> 5 votes
# Stax, 5 bytes

```
|d1=^

```

Run and debug it

Run and debug itRun and debug it

Run and debug itRun and debug itRun and debug it

This works for `m = 2, n = 1`.

# Answer
> 5 votes
# Charcoal, 11 bytes

```
⎚⊞υω×1⁼³Ｌυ5

```

\\$n=5\\$, \\$m=3\\$. Try it online! Try it online!Try it online! Try it online!Try it online!Try it online! Try it online!Try it online!Try it online!Try it online! Explanation:

Clear the canvas of output from the previous copy.

```
⊞υω

```

Track the number of copies.

```
×1⁼³Ｌυ

```

If that's 3 then print a `1`.

```
5

```

Always print a `5`.

# Answer
> 4 votes
# JavaScript, ~~65~~ ~~60~~ ~~57~~ ~~46~~ 45 bytes, \\$n = 1, m = 5\\$

```
var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));

```

*Saved 3 bytes thanks to Arnauld.*

*Saved 11 bytes thanks to user81655*

*Saved 1 byte thanks to Neil*

By itself:

```
var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));
```

Repeated 5 times:

```
var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));
```

# Answer
> 4 votes
# Zsh `-F`, 21 bytes, \\$n=1\\$, \\$m=4\\$

```
bye `wc -l<$0`-5?1:4

```

Try it online!

Try it online!Try it online!Try it online!Try it online!

Note the trailing newline. Outputs via exit code.

# Answer
> 4 votes
# Factor, 172 bytes, n = 2, m = 4

Let's see some love for the language of the month.

```
 USING: prettyprint namespaces init math io kernel ; IN: main 0 1 set-global
1 get-global 1 + 1 set-global [ 1 get-global 4 = [ 8 ] [ 2 ] if . flush ] 2 add-shutdown-hook !

```

(The leading space before `USING:` is significant, and so is the lack of newline at the end)

We store a simple counter in a global variable (global variables in Factor are, by convention, symbols, but there's no actual requirement, so our global variable is named the integer `1`). Then the part of our code that "repeats" simply increments this global. We register a shutdown hook that does the final checks for us. The fact that we register the hook several times is irrelevant, because we give it the same name each time (this name, incidentally, is the integer `2`; once again, Factor is happy to accept a very loose definition of "name").

Try it online!

Try it online!Try it online!

Try it online!Try it online!Try it online!

Try it online!Try it online!Try it online!Try it online!

# Answer
> 3 votes
# 05AB1E, ~~6~~ ~~5~~ 4 bytes, \\$ n=1, m=2 \\$

-1 thanks to @Kevin Cruijssen

```
.gΘ>

```

Try it online!

# Answer
> 3 votes
# Java 6, ~~120~~ 77 bytes, \\$n=1, m=2\\$

```
enum A{A;{System.out.print(new java.io.File("A.java").length()==154?2:1);}}//

```

*Saved 43 bytes thanks to Olivier Grégoire.*

# Answer
> 2 votes
# Japt, ~~8~~ 6 bytes, \\$n=1\\$, \\$m=2\\$

Works because Javascript numbers don't overflow from positive to negative.
Essentially J is incremented to infinity, 2 is output only on the case of two repetitions.

```
J°?1:2 // J is a builtin variable that equals -1 at first.
J°     // If J++ is truthy (-1, 1, 2, etc)
  ?1:2 // output 1, otherwise 2.

```

Try it here.

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

```
0;i=-~this.i,{get x(){print(i-3?1:3)}}.x

```

Try it online!

Uses the same trick as my solution the other day. The core idea is putting the `print()` behind a getter function. If the `.x` property is accessed it will print the result. This is placed at the end of the generated code so that it accesses `.x` on the last iteration but when concatenated it becomes `.x0` (does not access `.x`).

# Answer
> 2 votes
# JavaScript (Node.js), 26 bytes, \\$n=1\\$, \\$m=2\\$

```
(x=>x?y=>y?g=z=>z?g:1:2:1)

```

Try it online!

Is this valid? I'm not quite sure...

---

# JavaScript (SpiderMonkey), 28 bytes, \\$n=1\\$, \\$m=2\\$

```
f=x=>((f+'').length==54)+1//

```

Try it online!

Another similar answer (requires Firefox 86**-**)

# Answer
> 2 votes
# Julia, 20 bytes, \\$n=1\\$, \\$m=2\\$

```
a=b=1;a+=1;b+=a==3;b

```

Try it online!

# Answer
> 2 votes
# PHP, ~~38~~ 34 bytes \\$n=1\\$ \\$m=2\\$

```
<?=count(file(__FILE__))!=3?:2;
//

```

Try it online!

This hacky solution relies on getting the current code's first line and testing the length is 76 (38 * 2). Works as a standalone but needs the `//` to comment any repetitions of the program so that only one output is displayed. Also in ternary conditions `a?b:c`, if `b` is missing, the value of `a` is used, and in PHP `true` is displayed as `1`.

EDIT: saved 4 bytes by counting the lines of code instead of length of the first line. Notice the newline *before* the comment

# Answer
> 2 votes
# Brainfuck, 268264 characters / 10199 bytes, n=1, m=2

```
    ++>+ Init
    [->+>+<<]>>[-<<+>>]< Copy second into third
    [-<<->>]<< Check if equal
        [ If not equal
            [-] Reset first
            +++++++++++++++++++++++++++++++++++++++++++++++++
            .
            ------------------------------------------------- Output 1
            >>>-<<< Set a flag saying that this cycle was passed
        ]
        >>>+ Change the flag
        [ If the flag is nonzero (meaning the previous cycle was not passed)
            [-] Reset the flag
            ++++++++++++++++++++++++++++++++++++++++++++++++++
            .
            -------------------------------------------------- Output 2
        ]
    <[-]<<[-] Reset first and third

```

Try it online!

This can take a while to run, so set the delay to minimum if you want to test it.

Definitely not a good golfing language, but it was interesting to write just for the sake of it.

(This challenge is impossible to complete in BF as it's stated because repeated code will always produce a multiple-char output, so in this solution the answer is the last output char)

Edit: I'm completely brain dead and forgot this is code golf, so I wrote the last lines in a really weird way. Corrected, saved 4 chars.

# Answer
> 2 votes
# Grok, 31 bytes, n=1, m=2

```
`  j
ljq
11z
+=1
 {k
j2`h
`lzq

```

Note the single trailing newline. Program was multiplied with `cat odd1out >> odd2out`. At first I thought I would have to rework my solution because of how programs need to be multiplied, but then I realized I could just turn it on its side.

---
Tags: code-golf, source-layout
---


title: The Great Pyramid of ASCII

text:
# Question
Title: The Great Pyramid of ASCII
### Introduction

It's 2600 BC and people are building pyramids now. They already made the basis of the pyramid but don't know how to continue. So, they called you for help.

The rules of making a pyramid is quite simple. For the layer above the previous layer, all you need to do is follow this step-by-step hand guide:

1. Cut the edges off the previous layer.
2. Above the `/` character, there must be a `\` character and vice versa. This applies to every character **except** the edges.
3. The leftmost character is always a `/` and the rightmost character is always `\`.

Let's take an example of a basis for a pyramid:

```
//\/\/\\

```

We cut off the edges, leaving:

```
 /\/\/\

```

We change the forward slashes with backward slashes and vice versa:

```
 \/\/\/

```

The leftmost character is always a `/` and the rightmost character is always a `\`, so we change that:

```
 //\/\\

```

We place this layer on the previous layer:

```
 //\/\\
//\/\/\\

```

We continue until the top is reached (which looks like `/\`). So, eventually we get:

```
   /\
  //\\
 //\/\\
//\/\/\\

```

This is what you need to output.

### The task

Given the basis of a pyramid (with a length greater than 3), output the full pyramid. You can safely assume that the leftmost character is `/` and the rightmost character is a `\`. You can also assume that the length of the basis is always **even**. The use of **trailing spaces** is allowed. The use of **leading spaces** is also allowed, as long as the pyramid stays in place. The use of 1 **trailing** and 1 **leading** newlines is allowed.

### Test cases

```
Input: /\\\
Output:
 /\
/\\\

Input: //\\///\/\
Output:
    /\
   /\\\
  /\///\
 ///\\\/\
//\\///\/\

Input: /////////////\
Output:
      /\
     /\\\
    /////\
   /\\\\\\\
  /////////\
 /\\\\\\\\\\\
/////////////\

```

This is , so the submission with the least amount of bytes wins!

# Answer
# Jelly, ~~28 26 25~~ 24 bytes

```
QṚ,QyḊḊṖṖj@QµÐĿµJ’⁶ẋ⁸żYṚ

```

-4 bytes thanks to Dennis

Recipe:

```
QṚ,QyḊḊṖṖj@QµÐĿµJ’⁶ẋ⁸żYṚ - one argument: input()
Q  Q       Q             - set of Left=input(): "/\"
 Ṛ                       - reverse Left: "\/"
  ,                      - Left-pair-Right: ["\/","/\"]
     ḊḊṖṖ                - dequeue Left twice, then pop twice: input()[2:-2]
    y                    - translate Right with mapping in Left: swaps internal slashes
         j@              - join Right with separator Left (@ swaps operands)
            µ  µ         - chain separators to form a 1,1,1 chain of chains
             ÐĿ          - loop while results are unique and collect them
                J        - yield [1,...,len(Left=input())]
                 ’       - decrement: [0,....len(input())-1]
                  ⁶      - " "
                   ẋ     - repeat Left Right times: ["", " ", ...]
                    ⁸ż   - zip Right and Left (⁸ is the link's Left argument):
                                ...pads the loop results
                      Y  - joins Left with line-feeds
                       Ṛ - reverse Left

```

*(serve with lemonade, those pyramids make for thirsty workers)*

Cook up your own slash pyramid at **TryItOnline**, or try out all the OP's suggested tasters
> 9 votes

# Answer
# Retina, ~~59~~ ~~56~~ ~~54~~ 52 bytes

```
{`^( *)/.(.*)..
$1 /$2\¶$0
T`/\\`Ro`(?<=^ +/).+(?=.)

```

Try it online!

## Sample output

```
    /\
   /\\\
  /\///\
 ///\\\/\
//\\///\/\

```
> 12 votes

# Answer
# Pyth - ~~27~~ 26 bytes

Reduces by the operation given in the OP until it repeats, which is the case for the blank line.

```
j_.e+*kdb.ujXtPtPNK"\/")_K

```

Test Suite.
> 11 votes

# Answer
## Python 2, 78 bytes

```
f=lambda s,p='\n':(s[2:]and f('/%s\\'%s.translate('/\\'*128)[2:-2],p+' '))+p+s

```

A recursive function that outputs a string. Each layer of the pyramid is appended to the recursive call with the layer above it. The prefix `p`, which starts as a newline character gains one more space to make the triangle. The next layer is produced by swapping slashes, cutting off the first and last two symbols, and sandwiching it inside a left and right slash.

Python 3 can save a byte by doing `*99` in the `translate`, as the length-256 requirement was dropped.
> 8 votes

# Answer
## Haskell, ~~98~~ ~~94~~ ~~90~~ 85 bytes

```
q=init.tail
s '/'='\\'
s _='/'
t#""=t++"\\\n"
t#l=(' ':t)#(s<$>q l)++t++l#""
("/"#).q

```

Usage example (note: in Haskell backslashes within literal strings have to be escaped `\\`):

```
*Main> putStr $ (("/"#).q) "//\\\\///\\/\\"
    /\
   /\\\
  /\///\
 ///\\\/\
//\\///\/\

```

Simple recurse approach: `#` does the work by mapping `s`, which flips the `/` and `\`, on the inner elements. The additional parameter `t` keeps track of the indention level and is expanded by a space on each recursive call.

Note: the second recursive call of `#` (-\> `l#""`) jumps directly to the base case and is just a short way to add `l`, `\` and a newline, i.e. it replaces `++l++"\\\n"`.

Edit: @xnor saved 5 bytes. Thanks!
> 7 votes

# Answer
# Python 3, ~~108 104 101 94 91 89~~ 88 bytes

```
b,f='\/';p=lambda t,n='\n':(t[2:]and p(f+''.join(map({f:b,b:f}.get,t[2:-2]))+b,n+' '))+n+t

```

-7 bytes thanks to xnor (letting me know we don't have to print!)
-3 bytes thanks to xnor (taking declaration outside of function declaration \[d'oh\])
-1 byte thanks to Dennis (replace `f,b='/\\'` with `b,f='\/'`)

Test it on **ideone**. Note: input adjusted for double backslash (even raw strings won't work if they end in an odd number of backslashes).
> 6 votes

# Answer
## JavaScript (ES6), ~~91~~ 86 bytes

```
f=
(s,t=`
`)=>s[2]?f(`/${s.slice(2,-2).replace(/./g,c=>c>`/`?`/`:`\\`)}\\`,t+` `)+t+s:t+s
;
```

```
<input placeholder=Basis oninput=o.textContent=f(this.value)><pre id=o>
```

Output includes a leading newline character.
> 5 votes

# Answer
# Ruby, 80 bytes

```
f=->s{s[-3]>?!&&f[" "+s.gsub(/^( *\/).|.(.$)?/){$1||$2||($&>?/??/:?\\)}]
puts s}

```

## Ungolfed

```
f = ->s{
  s[-3] > ?! &&
    f[" " + s.gsub(/^( *\/).|.(.$)?/) {
      $1 || $2 || ($& > ?/ ? ?/ : ?\\)
    }]
  puts s
}

```

See it on ideone: http://ideone.com/HN0l0Y
> 3 votes

# Answer
## Batch, 137 bytes

```
@echo off
if %1==/\ goto g
set s=%1
set s=\%s:~2,-2%/
set s=%s:/=-%
set s=%s:\=/%
set s=%s:-=\%
call %0 %s% "%~2 "
:g
echo %~2%1

```

Conveniently my use of`%~2` and `%1` means that I avoid having to spend bytes on `setlocal`. Explanation: Since Batch won't perform replacements on the empty string, we have to set up the next layer with the "wrong" edges, which will then be corrected as part of the string replacements.
> 3 votes

# Answer
# 05AB1E, ~~42~~ ~~38~~ 36 bytes

```
Dg;<FÐgÍ©£R®ÍN-£„/\Â‡'/ðN>×««R'\«}r»

```

Try it online!

Explanation:

```
# Read the input to the stack, loop for 0 .. len(input) / 2 - 1
Dg;<F
# Save the layer by pushing a copy on the stack, then push
# len(layer) - 2 to both the top of the stack and register_c
     ÐgÍ©
# a = pop(); b = pop(); push(b[0:a].reverse())
# This removes the last 2 characters and reverses
         £R
# push(register_c - 2 - N)
           ®ÍN-
# a = pop(); b = pop(); push(b[0:a])
# This removes the leading spaces and the first two slashes
               £
# Push "/\" and "\/" to the stack.
                 „/\Â
# Transliterate the slashes
                     ‡
# Add N+1 spaces and a / to the end of the (reversed) current layer
                      '/ðN>×««
# Reverse the layer and add a \ to the end.
                              R'\«
# End the loop
                                  }
# Reverse the stack and join it with newlines. It is implicitly printed.
                                   r»

```

(Thanks to Emigna for pointing out that `DD -> Ð` and `DR -> Â`).
> 2 votes

# Answer
# BASH (sed + sort) 71 66 Bytes

```
~~sed -rne':l;p;y|\\|1|;y|/|\\|;y|1|/|;th;:h;s|\\.(.*)./| /\1\\|;tl'|sort~~
sed -rne':l;p;y|\\/|1\\|;y|1|/|;th;:h;s|\\.(.*)./| /\1\\|;tl'|sort

```

input comes from stdin.
Example:

```
echo '//\\' |sed -rne':l;p;y|\\|1|;y|/|\\|;y|1|/|;th;:h;s|\\.(.*)./| /\1\\|;tl'|sort

 /\
/\\\

```

Explanation:
`-n` \- suppress auto print
`:l` \- and `tl` branch back to the beginning if this line was something other than `/\`
`p` \- print this line
`y|\\/|1\\|;y|1|/|` \- replace `\` with `1`, `/` with `\`, and then `1` with `/`
`th;:h` \- test and jump the the same place, so that only the next substitution gets tested later
`s|\\.(.*)./| /\1\\|` \- replace the outside two slashed on each side with `{space}/` and `\`
`sort` \- `space` comes before `/` so this puts everything in the right order
> 2 votes

# Answer
# Go, ~~300~~ 276 bytes

```
package main
import(."regexp";."os")
func p(b string)string{
s:=MustCompile(`((\s*.)(\S*)(\S))`).FindStringSubmatch(b)
if s[3]!=""{r:=""
for _,c:=range s[3][1:len(s[3])-1]{r+=`\/`[c/64:c/46]}
return p(" "+s[2]+r+`\`)+s[1]+"\n"}
return s[1]+"\n"}
func main(){print(p(Args[1]))}

```

Long version:

```
package main

import (
    "regexp"
    "os"
)

func pyramid(base string) string {
    m := regexp.MustCompile(`^((\s*\S)(\S*)(\S))\s*`).FindStringSubmatch(base)
    if len(m[3]) > 0 {
        reversed := ""
        for _, c := range m[3][1:len(m[3]) - 1] {
            if c == '/' {
                reversed += `\`
            } else {
                reversed += `/`
            }
        }
        return pyramid(" " + m[2] + reversed + m[4]) + m[1] + "\n"
    }
    return m[1] + "\n"
}

func main() {
    print(pyramid(os.Args[1]))
}

```
> 1 votes

# Answer
## \>\<\>, ~~186~~ ~~179~~ ~~175~~ 171 bytes

```
0&v &+1&<
  >i:0)?^~&2,:&v
v'/'~v?:-1<  }0<
o    >84*o^-$;?=@:&:&}:~<
\&::&{:@+$}1+[{l1-$-2*:&1+{
>}1-:?!v$:l2%?!vo
^o'/'v?~e  (*5a<
^o'\'< &   >~]a'\'oo{1+:^
  {$1- >:?!^

```

oooh man this is definitely my largest \>\<\> answer yet.

There's still probably some golfing left to be done (the bottom area is pretty wasteful)

Try it online
> 1 votes

# Answer
# Perl, ~~53~~ 52 bytes

Includes +1 for `-p`

Run with the input on STDIN, e.g.

```
./pyramid.pl <<< '//\\///\/\'

```

`pyramid.pl`:

```
#!/usr/bin/perl -p
s%^( *)/.(.*)..%"$1 \\$2/
"=~y|\\/|/\\|r.$&%e&&redo

```
> 1 votes

# Answer
# 05AB1E, 31 bytes

```
Dg;GDðK¦¦¨¨„/\Â‡'\«R'/«ðN×«R}r»

```

**Explanation**

```
Dg;G                        }    # for N in [1..len(input)/2-1]
    D                            # make a copy of previous layer
     ðK                          # remove all spaces
       ¦¦¨¨                      # remove first 2 and last 2 chars
           „/\Â‡                 # replace '/' with '\' and vice versa
                '\«              # add a backslash at the end
                   R             # reverse
                    '/«          # ad a slash at the end
                       ðN×«      # add N spaces
                           R     # reverse back
                             r»  # reverse stack and join on newline
                                 # implicitly print

```

Try it online
> 1 votes

# Answer
## Powershell, 142 bytes

```
function s($s){if($s.Trim()-eq'/\'){return $s}
$n=$s-replace'\\','#'-replace'/','\'-replace'#','/'-replace'\\.(.*)./',' /$1\'
(s($n))+"`n$s"
}

```
> 0 votes

# Answer
## C#, 250 bytes

```
s=>{int j=s.Length/2,i=0;var l=new string[j];l[j-1]=s;while(++i<j){var n=l[j-i].Trim().Substring(1,l[j-i].Trim().Length-2);l[j-i-1]=new string(' ',i)+"/"+n.Replace("/","#").Replace(@"\","/").Replace("#",@"\").Substring(1,n.Length-2)+@"\";}return l;};

```

Can definitely be golfed further but my brain went dead so I decided to leave it as it is for the moment.
> 0 votes

# Answer
# Stax, 22 bytes

```
à╝á■╬h½₧£Hδuóß►Δδ£ƒ┐#R

```

Run and debug it
> 0 votes

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


title: Translate a Glypho program

text:
# Question
Title: Translate a Glypho program
Given an input of any valid Glypho program, output its "human-readable" counterpart.

Glypho is an interesting esolang idea:

> The instruction reference is given here. For each instruction, the characters abcd represent the symbols composing each instruction. a refers to the first unique symbol, b refers to the second unique symbol, etc.
>
> ```
> aaaa ..... n NOP - no operation; do nothing
> aaab ..... i Input - push input onto top of stack
> aaba ..... > Rot - pops top stack element and pushes to bottom of stack
> aabb ..... \ Swap - swaps top two stack elements
> aabc ..... 1 Push - pushes a 1 onto the top of stack (creates new element)
> abaa ..... < RRot - pops bottom element and pushes to top of stack
> abab ..... d Dup - Duplicates top stack element
> abac ..... + Add - pops top two elements and pushes their sum
> abba ..... [ L-brace - skip to matching ] if top stack element is 0
> abbb ..... o Output - pops and outputs top stack element
> abbc ..... * Multiply - pops top two elements and pushes their product
> abca ..... e Execute - Pops four elements and interprets them as an instruction
> abcb ..... - Negate - pops value from stack, pushes -(value)
> abcc ..... ! Pop - pops and discards top stack element
> abcd ..... ] R-brace - skip back to matching [
>
> ```
>
> <sub>(credit: Brian Thompson aka Wildhalcyon)</sub>

So, for example, `PPCG` would represent the *Push* instruction—`PPCG` matches the pattern `aabc`, where `a` represents `P`, `b` represents `C`, and `c` represents `G`.

The input will be a single string consisting of only printable ASCII characters. It will always have a length divisible by four (duh).

The output is each group of four characters in the input string replaced by which instruction they designate. Use the single-letter instruction names (the ones right after the five dots in the table quoted above).

Since this is , the shortest code in bytes will win.

Test cases:

```
In                                Out
------------------------------------------------
Programming Puzzles & Code Golof  ]!]!]]]+
nananananananana batman!          dddd]]
;;;;;;;:;;:;;;::                  ni>\
llamas sleep                      1-*
8488133190003453                  <[oe
<empty string>                    <empty string>

```

# Answer
# Pyth, ~~37~~ ~~35~~ 34 bytes

The code contains unprintable characters, so here is the `xxd` hexdump:

```
0000000: 5663 7a34 7040 2e22 216f d78c 40bf d4f0  Vcz4p@."!o..@...
0000010: 38d6 7dfe 7312 3ff8 ea22 6958 4e7b 4e55  8.}.s.?.."iXN{NU
0000020: 5433                                     T3

```

Here's a printable version at 36 bytes:

```
Vcz4p@"ni >\\1   <d+[o*e-!]"iXN{NUT3

```

Try it online. Test suite.

### Explanation

```
Vcz4p@."…"iXN{NUT3       implicit: z = input
  z                      input
 c 4                     split to 4-character blocks
V                        loop over that in N
           X               replace...
            N                in current part
             {N              unique chars in current part, in order
               UT            with numbers 0-9
          i      3         interpret as base 3
     @                     take that item of
      ."…"                   string "ni >\\1   <d+[o*e-!]"
    p                      and print without newline

```
> 5 votes

# Answer
## CJam, ~~42~~ ~~39~~ 35 bytes

*Saved 4 bytes borrowing user81655's idea of using base 3 instead of base 4.*

```
l4/{__&f#3b"ni >\1   <d+[o*e-!]"=}%

```

Run all test cases.

There's gotta be a better way to compress the lookup table of commands...
> 4 votes

# Answer
# JavaScript (ES6), 97

For each block of 4 characters, I substitute each symbol with its position in the block, getting a base 4 number. For instance `'aabc' -> '0023'`. The possibile numbers are in the range 0..0123, that is 0..27 in decimal. I use the number as an index to find the right instruction character from a 28 chars string.

```
s=>s.replace(/.{4}/g,s=>'n..i....>.\\1....<d.+[o.*e-!]'[[...s].map(c=>n=n*4+s.indexOf(c),n=0),n])

```

**Test**

```
F=s=>s.replace(/.{4}/g,s=>'n..i....>.\\1....<d.+[o.*e-!]'[[...s].map(c=>n=n*4+s.indexOf(c),n=0),n])

function test() { O.textContent=F(I.value) }

test();
```

```
#I { width:90% }
```

```
<input id=I value="nananananananana batman!" oninput="test()">
<br><span id=O></span>
```
> 4 votes

# Answer
# MATLAB, 291 bytes

I hesitated for quite a long time if I should commit my answer. I was just playing around with MATLAB. I am aware that it's not really possible to generate dense code (a low number of instructions/bytes; about 3 times larget than your ~100 byte solutions) and that MATLAB might not be too suitable for code golf and I am new to code golf. But I simply wanted to try, and the code works (newline characters kept). Any hints welcome. :P

```
i=input('','s');
l=reshape(i,4,length(i)/4)';
m=']!- e';m(9)='*';m(12:22)='o[   + d  <';m(33:34)='1\';m(39)='>';m(57)='i';m(64)='n';
s='';
for k = 1:size(l,1)
n=l(k,:);
c=combvec(n,n);
t=triu(reshape(c(1,:)==c(2,:),4,4),1);
t=sum(t([5,9:10,13:15]).*2.^[5:-1:0]);
s=[s,m(t+1)];
end
display(s)

```
> 4 votes

# Answer
# JavaScript (ES6), ~~115~~ 101 bytes

```
s=>s.replace(/..../g,g=>"ni >\\1   <d+[o*e-!]"[[...g].map(c=>r=r*3+(m[c]=m[c]||++i)-1,i=r=0,m={})|r])

```

*Saved 14 bytes thanks to @edc65!*

## Explanation

Stores the list of instructions in a string with each character at it's base-3 index. For example, `+` corresponds to `abac` which can be represented in base-3 as `0102`, or `11` in decimal. The only instruction that cannot be represented in base-3 is `]`, but with the algorithm used to compute the base-3 number, it conveniently ends up needing to be at position 18 at the end of the string.

```
s=>
  s.replace(/..../g,g=>    // replace each four-character group with it's instruction
    "ni >\\1   <d+[o*e-!]" // list of instructions at their base-3 index
    [
      [...g].map(c=>       // for each character c
        r=r*3+(m[c]=m[c]   // shift r left and add the number associated with c to r
          ||++i)-1,        // if nothing is associated, associate the next number to c
                           // save i + 1 to m[c] so that it is truthy for 0
        i=                 // i = current number to assign to the next unique character
        r=0,               // r = 4-character group as a base-3 number
        m={}               // m = map of numbers assigned to each character
      )
      |r                   // return r
    ]
  )

```

## Test

```
var solution = s=>s.replace(/..../g,g=>"ni >\\1   <d+[o*e-!]"[[...g].map(c=>r=r*3+(m[c]=m[c]||++i)-1,i=r=0,m={})|r])
```

```
<input type="text" id="input" value="Programming Puzzles & Code Golof" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 3 votes

# Answer
# Python 2, 158 bytes

Takes input like `"test"`. Output is a list of characters.

```
def b(s,i=0):
    for c in s:i=i*4+s.index(c)
    return"n..i....>.\\1....<d.+[o.*e-!]"[i]
print map(b,(lambda l,n:[l[i:i+n]for i in range(0,len(l),n)])(input(),4))

```

**Try it Online!**

**Ungolfed:**

```
def chunks(l, n):
    return (l[i:i+n] for i in range(0, len(l), n))

def convert(inst):
    i = 0
    for c in inst:
        i = i*4 + inst.index(c)

    return "n..i....>.\\1....<d.+[o.*e-!]"[i]

print map(convert, chunks(input(), 4))

```
> 1 votes

# Answer
# Zsh, 118 bytes

```
0="n  i      > \1${(l:11:)}<d + [o * e-!]"
for s (`tr \  £|fold -4`)(eval ';n+=$s[(i)$s['{2..4}]];printf $0[5#$n-30])

```

Try it online!

* `0="n i > \1${(l:11:)}<d + [o * e-!]"` \- store this string in the variable `$0`. `${(l:11:)}` generates 11 spaces (literally, left-padding an empty string to a length of 11), and is 1 byte shorter than writing them literally.
* `tr \ £` \- replace spaces (`\` ) with `£`s. This is because spaces in the input will be eaten when word splitting, messing up the 4 character grouping. Word splitting is useful though, because it allows us to loop over each line, which is how `fold` splits things. I used `£` because it's outside the printable ASCII range that we're required to accept and only 2 bytes in UTF-8 (I could probably technically save a byte if I used a different encoding, but that's not worth the effort). Unfortunately I can't use a control character because `zsh` doesn't like them.
* `fold -4` \- group into 4 characters per line
* `for s (``)` \- for each group, `$s`, of 4 characters:
    + `';n+=$s[(i)$s['{2..4}]]`: generate the string `;n+=$s[(i)$s[2]];n+=$s[(i)$s[3]];n+=$s[(i)$s[4]]`
    + `eval`uate that as `zsh` code:
        - `$s[X]` \- the `X`th character of `$s` (1-indexed)
        - `$s[(i)]` \- find the index of the first appearance of that character within `$s`
        - `n+=` \- append that to `$n` (which implicitly starts out empty)
        - `eval` with brace expansion (like `{2..4}`) is a shorter way to do a simple loop than using `for`
        - We only need to use `{2..4}` as the first index of the first character of the string will obviously always be `1`. This lets us save a byte when subtracting later (otherwise it would be -155 rather than -30)
        - `5#$n` \- interpret `n` as a base-5 integer (if zsh used 0-based indexing, this could be base 4, we wouldn't need to subtract anything, and the `$0` string could be shorter)
    + `-30` \- the minimum base-5 value we can get from any combination of characters is `31`, and since `zsh` is 1-indexed, we subtract 30 to get an index into the string `$0`
    + `$0[]` \- get that index into the string `$0` for the relevant character to print. The spaces in `$0` are padding to make the right characters appear in the right places since the possible base-5 values aren't contiguous.
    + `printf` \- print that with no newline
        - `()` \- subshell; any changes to variables do not persist outside the brackets. This is used to reset `$n` to an empty string on each iteration.
> 1 votes

# Answer
# , 37 bytes

```
'ni >\1   <d+[o*e-!]'{~_4(3#.~.i.])\]

```

Try it online!
> 1 votes

---
Tags: code-golf, string, parsing, syntax
---


title: Recursive Binary Description

text:
# Question
Title: Recursive Binary Description
# Recursive Binary Description

Recently, I made my very first contribution to OEIS by extending and adding a b-file to sequence A049064. The sequence starts with `0`, and then the next values are derived from giving a "binary description" of the last item.

For example, the second term would be `10`, because there was one `0` in the first element. The third term would be `1110`, because there was one `1` and one `0`. The fourth would be `11110`. because there are three **(`11` in binary!)** `1`s and one `0`. Below is a breakdown of the fifth term to make this process clear:

```
> 11110
> 1111 0    (split into groups of each number)
> 4*1 1*0   (get count of each number in each group)
> 100*1 1*0 (convert counts to binary)
> 100110    (join each group back together)

```

And here's an example for going from the 6th to the 7th term:

```
> 1110010110
> 111 00 1 0 11 0
> 3*1 2*0 1*1 1*0 2*1 1*0
> 11*1 10*0 1*1 1*0 10*1 1*0
> 111100111010110

```

You can check out a reference programφ I made to calculate the terms.

# Your Job

You need to create a *program or function* which takes in a number `n` via *standard input or function arguments*, and prints out the sequence from the `1st` term to the `(n+1)th` term, separated by a newline. If you would like a look at the lower numbers, you may refer to the b-file from the OEIS page. However, your program/function should support `0 <= n <= 30`, i.e. up to the 31st term. This is no small feat, as `A049064(30)` is over 140,000 digits longδ. If you would like to see what the 31st term should be, I've put it on Pastebin.

# Example I/O

```
func(10)
0
10
1110
11110
100110
1110010110
111100111010110
100110011110111010110
1110010110010011011110111010110
1111001110101100111001011010011011110111010110
1001100111101110101100111100111010110111001011010011011110111010110

func(0)
0

func(3)
0
10
1110
11110

```

There is only one rule: **No standard loopholes!**

This is , so the lowest byte count wins.

---

φ - Gist can be found here, and an ideone demo is here.

δ - Just in case you were wondering, my estimates at the length of the 100th term put it at approximately 3.28x10250 characters long, which would be quite a lot for anyone to calculate.

# Answer
# CJam, ~~18~~ 17 bytes

```
0{sN1$e`2af.b}ri*

```

*Thanks to @MartinBüttner for golfing off one byte!*

Try it online in the CJam interpreter.

### How it works

```
0                 e# Push 0.
 {           }ri* e# Repeat int(input)) times:
  s               e#   Stringify the element on top of the stack.
                       EXAMPLE: [[[1 1] '1] [[1] '0]] -> "11110"
   N              e#   Push a linefeed.
    1$            e#   Copy the last stack.
      e`          e#   Perform run-length encoding.
                  e#   EXAMPLE: "100110" -> [[1 '1] [2 '0] [2 '1] [1 '0]]
        2a        e#   Push [2].
          f.b     e#   For each pair [x 'y], execute: [x 'y][2].b
                  e#   This pushes [x2b 'y], where b is base conversion.

```
> 8 votes

# Answer
# Pyth, ~~18~~ 17 bytes

```
J]0VQjk~JsjR2srJ8

```

Try it online: Demonstration

Thanks to @isaacg for saving one byte.

### Explanation:

```
                     implicit: Q = input number
 ]0                  create an initial list [0]
J                    and store in J
   VQ                for loop, repeat Q times:
              rJ8       run-length-encoding of J
             s          sum, unfolds lists
          jR2           convert each value to base 2
         s              sum, unfolds lists
       ~J               store the result in J

                        but return the old list,
     jk                 join it and print it

```

This uses the fact, that 0 and 1 in binary are also 0 and 1.
> 4 votes

# Answer
# Python 2, ~~125~~ ~~116~~ 110 bytes

```
from itertools import*
v='0'
exec"print v;v=''.join(bin(len(list(g)))[2:]+k for k,g in groupby(v));"*-~input()

```

Saved 1 byte thanks to @Sp3000 and 5 bytes by removing a redundant `int` call.

Older version:

```
import itertools as t
v='0'
exec"print v;v=''.join(bin(int(len(list(g))))[2:]+k for k,g in t.groupby(v));"*-~input()

```

Saved many, many bytes thanks to @Vioz-!

Original version:

```
import itertools as t
v='0'
for n in range(input()+1):print v;v=''.join(bin(int(len(list(g))))[2:]+k for k,g in t.groupby(v))

```
> 2 votes

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

```
{,/{(,/$2\#x),*x}'(&~~':x)_x}\[;,"0"]

```

Try it online!

* `{...}\[;,"0"]` set up a scan, seeded with `,"0"` and run for a number of times equal to the (implicit) input
* `(&~~':x)_x` split into groups of the same characters
* `{...}'` for each group...

+ `(,/$2\#x)` get the binary representation of the count of each group
    + `(...),*x` append the first character of each group (i.e. whether it is a group of `0`s or of `1`s)
* `,/` flatten the results and feed to the next iteration of the scan
> 2 votes

# Answer
# Ruby, ~~80~~ ~~72~~ 69 bytes

As a function:

```
f=->m{l=?0;0.upto(m){puts l;l.gsub!(/1+|0+/){$&.size.to_s(2)+$&[0]}}}

```

Call it for example with: `f[6]`
> 1 votes

# Answer
# Python 2, 102 bytes

```
import re
o='0'
exec"print o;o=''.join(bin(len(x))[2:]+x[0]for x in re.findall('0+|1+',o));"*-~input()

```

Somehow the combination of `itertools` being longer than `re` and `groupby` returning `grouper` objects means that using regex is a bit shorter...
> 1 votes

# Answer
# Jelly, ~~16~~ 14 bytes

```
µṄŒrUFV€BFṾ€ø¡

```

Try it online!

~~I still feel like there's some better way to do the string printing.~~

-2 bytes from xigoi.
> 1 votes

# Answer
# Jelly, 9 bytes

```
ŒrUBFƲÐ¡Y

```

Try it online!

Takes input from STDIN.

## Explanation

```
ŒrUBFƲÐ¡Y   Main niladic link
            Implicitly start with 0
      Ð¡    Repeat [number from STDIN] times and collect all values
     Ʋ      (
Œr            Run-length encode -> [[digit, repetitions], ...]
  U           Reverse each sublist -> [[repetitions, digit], ...]
   B          Convert all numbers to binary
    F         Flatten
     Ʋ      )
        Y   Join by newlines
            The numbers are automatically concatenated

```
> 1 votes

# Answer
# Haskell, ~~136~~ 130 Bytes

```
import Text.Printf
import Data.List
f n=putStr.unlines.take(n+1).iterate(concatMap(\n->(printf"%b"$length n)++[head n]).group)$"0"

```
> 0 votes

# Answer
# Cobra - 128

```
do(i)=if(i-=1,(r=RegularExpressions).Regex.replace(f(i),'1+|0+',do(m=r.Match())=Convert.toString('[m]'.length,2)+'[m]'[:1]),'0')

```
> 0 votes

# Answer
# Stax, 12 bytes

```
î╩∩▬╒«ç╚¢↓}~

```

Run and debug it
> 0 votes

---
Tags: code-golf
---


title: The number of tilings of a grid

text:
# Question
Title: The number of tilings of a grid
**Setup:** A *block* is any rectangular array of squares, specified by its dimensions \\$(w,h)\\$. A *grid* is any finite ordered list of blocks. For example, \\$\lambda = ((3,2),(3,1),(1,2))\\$ defines a grid.

Let \\$\lambda\\$ and \\$\mu\\$ be two grids with equal area.

A *tiling of \\$\lambda\\$ by \\$\mu\\$* is any rearrangement of the squares of \\$\mu\\$ into the shape of \\$\lambda\\$ satisfying two properties:

1. horizontally adjacent squares of \\$\mu\\$ remain horizontally adjacent in \\$\lambda\\$, and
2. vertically adjacent squares of \\$\lambda\\$ come from vertically adjacent squares of \\$\mu\\$.

In other words, while rearranging one is allowed to make horizontal cuts to the blocks of \\$\mu\\$ but not vertical cuts, and one is allowed to place blocks into \\$\lambda\\$ side-by-side, but not on top of one another.

Two tilings of \\$\lambda\\$ by \\$\mu\\$ are considered *equivalent* if they can be rearranged into one another by any combination of either permuting squares within a column or reordering the columns of a block.

**Problem:** Write a function \\$T(\mu,\lambda)\\$ which computes the number of inequivalent tilings of a grid \\$\lambda\\$ by another grid \\$\mu\\$ of equal area.

**Specifications:** You may use any data type you would like to specify a grid.

**Examples:**

1. The grid \\$\lambda=((1,2),(1,2),(1,1),(2,1))\\$ admits a tiling by \\$\mu=((1,3),(1,2),(2,1))\\$ given by

There is exactly one other inequivalent tiling given by

(Since the two differently colored columns of height \\$2\\$ are not part of the same block, they cannot be permuted.)

2. The three displayed tilings of \\$\lambda=((3,1))\\$ by \\$\mu=((1,2),(1,1))\\$ are equivalent:

3. Let \\$\lambda\\$ be an arbitrary grid of area \\$n\\$ and let \\$\lambda\[(w,h)\]\\$ denote the number of blocks of \\$\lambda\\$ of dimension \\$w \times h\\$. Then \\$T(\lambda,\lambda) = \prod\_{w,h\geq 1} \lambda\[(w,h)\]!\\$ and \\$T(\lambda,((n,1))) = 1\\$.
4. The matrix of values of \\$T(\mu,\lambda)\\$ for all pairs of grids of area \\$3\\$ (row is \\$\mu\\$, column is \\$\lambda\\$):

|  | ((1,3)) | ((1,2),(1,1)) | ((1,1),(1,1),(1,1)) | ((2,1),(1,1)) | ((3,1)) |
| --- | --- | --- | --- | --- | --- |
| ((1,3)) | 1 | 1 | 1 | 1 | 1 |
| ((1,2),(1,1)) | 0 | 1 | 3 | 2 | 1 |
| ((1,1),(1,1),(1,1)) | 0 | 0 | 6 | 3 | 1 |
| ((2,1),(1,1)) | 0 | 0 | 0 | 1 | 1 |
| ((3,1)) | 0 | 0 | 0 | 0 | 1 |

# Answer
# Haskell, <sup>~~255~~~~247~~</sup> 242 bytes

* -2 bytes thanks to xnor, for suggesting a better partitioning function `q`.
* -8 bytes thanks to ovs, for suggesting `[a!!i|i:_<-u]` and removing an unnecessary `map`.

```
(a#b)c d=sum[1|g<-nub$(permutations(zipWith replicate b[0..]>>=id)>>=q)>>=mapM(q.sort),l g==l c,and[l x==h&&all(==x!!0)x&&sum[a!!i|i:_<-u]==w|(u,w,h)<-zip3 g c d,x<-u]]
q=foldr(\h t->map([h]:)t++[(h:y):z|y:z<-t])[[]]
l=length
import Data.List

```

Try it online!

A grid \\$\mu\\$ is represented as a pair \\$(W\_\mu,H\_\mu)\\$ where \\$W\_\mu\\$, \\$H\_\mu\\$ are lists containing, respectively, the widths and the heights of the blocks in \\$\mu\\$.

The relevant function is `(#)`, which takes as input four lists: `a`\\$=W\_\mu\\$, `b`\\$=H\_\mu\\$, `c`\\$=W\_\lambda\\$, `d`\\$=H\_\lambda\\$. It returns the integer \\$T(\mu,\lambda)\\$.
> 5 votes

---
Tags: code-golf, grid, set-partitions, tiling
---


title: Fastest draw in the west!

text:
# Question
Title: Fastest draw in the west!
We're going rootin' tootin' cow-poke shootin!

This is a simple contest, first program to draw their pistol wins.

### How it works:

* I require 2 things from you, an executable, and a command to be run from a bash terminal.
* The executable needs to do one thing: wait until it receives 'draw!' from STDIN, and then print 'bang!' as fast as possible, and exit.
* The executable can do anything else in the meantime, even print to STDOUT, as long as it doesn't print 'bang!', or feed itself from STDIN. It also can't use a standard loophole.
* Printing 'bang!' early, or exiting without printing 'bang!' is not allowed (you'll be one dead son of a gun).
* Bash, and other sh derivatives, including sh scripts are not allowed, we don't settle things on native land.

## How I measure your boot size:

* Using the golang runtime, I shall execute your command 1,000 times, the time it takes after feeding 'draw!' into STDIN to print 'bang!' will be your score, within +/- 2 nanoseconds. Your program will be given 500ms(+/-100ms of randomness) to stabilize, and load into memory. The program shall be run on ubuntu 20.04 server with only the necessary components to run your program installed.
* There will be the following categories: **Max** time, **Min** time, **Avg** time, and **Median** time, all with lower times being the best.

At the end of the month, the fastest gun in the wild west will be chosen. Best of luck!

# Answer
```
section .text

global _start

_start:
  xor r8, r8
  xor r9, r9
  xor r10, r10

_do_while:

_getchar:
  cmp r9, r10

  jne _getchar_done

_getchar_read_buffer:
  xor r9, r9

  xor eax, eax
  xor edi, edi
  mov rsi, in_buf
  mov rdx, inbuf_maxlen

  syscall

  mov r10, rax

_getchar_done:
  mov al, [in_buf + r9]
  inc r9

_do_while_cont:
  cmp al, [req + r8]

  jne _reset

_increment:
  inc r8

  cmp r8, 5

  jne _do_while

  mov rax, 1
  mov rdi, 1
  mov rsi, ans
  mov rdx, 5

  syscall

_end:
  mov rax, 60
  xor rdi, rdi

  syscall

_reset:
  xor r8, r8

  cmp al, 'd'

  jne _do_while

  inc r8

  jmp _do_while

section .rodata
  inbuf_maxlen equ 1000000

  req db "draw!"

ALIGN 8
  ans db "bang!"

section .bss
  in_buf resb inbuf_maxlen

```

A little hand-written assembly. Compile with:

```
nasm -felf64 foobar.s && ld foobar.o -o foobar

```

Edit: move `in_bi` into a register and use `xor`.

Edit: used the wrong jump, my code was wrong...

Edit: the previous code had a bug where it would read garbage if the `read` syscall did not return a full buffer. This version is more efficient (and correct)...

Edit: make sure to process `ddraw!` correctly. Thanks to Anders Kaseorg for the test case.

Edit: re-structure to move `getchar` out of a function and to jump less.

Edit: don't xor the high bits of the registers at the suggestion of Cody Gray

Edit: align (thanks to Joshua) and move into `.rodata`
> 12 votes

# Answer
# C

```
#include "stdio.h"

int main() {
  char* a = "draw!";
  int i = 0;
  char c;
  while (1) {
    if ((c = getchar()) == a[i]) {
      i++;
    } else {
      i = c == 'd';
    }
    if (i == 5) {
      puts("bang!");
      break;
    }
  }
}

```

Compiled with `gcc -O3 test.c`. You can get a copy of the executable here, but it is probably safer to just copy this code and compile it so you can be sure the executable isn't unsafe (I would never give malicious code online, but it is best to be cautious).

This isn't a very good solution, but it probably works as a baseline for other ideas.
> 8 votes

# Answer
# Java 11 (Oracle JDK)

Just curious about how it runs.

```
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

import static java.nio.charset.StandardCharsets.US_ASCII;

public class Main {

  public static void main(String[] args) throws IOException {
    var stateMachine = new int[6 * 256];
    var response = "bang!".getBytes(US_ASCII);
    Arrays.fill(stateMachine, 5 * 256);
    stateMachine[5 * 256 + 'd'] = stateMachine[4 * 256 + 'd'] = stateMachine[3 * 256 + 'd'] = stateMachine[2 * 256 + 'd'] = stateMachine[1 * 256 + 'd'] = 4 * 256;
    stateMachine[4 * 256 + 'r'] = 3 * 256;
    stateMachine[3 * 256 + 'a'] = 2 * 256;
    stateMachine[2 * 256 + 'w'] = 256;
    stateMachine[256 + '!'] = 0;

    var in = new FileInputStream(FileDescriptor.in);
    var out = new FileOutputStream(FileDescriptor.out);

    for (var state = 5 * 256; state != 0; ) {
      state = stateMachine[state | in.read()];
    }

    out.write(response, 0, 5);
    System.exit(0);
  }
}

```

Try it online!

Compile to bytecode with

```
javac Main.java

```

Run with

```
java -Xbatch Main

```

Note the `-Xbatch` is important as it will further precompile the bytecode to machine code. It's also important to run with Oracle JDK because it has the best machine compiler.

It will reach the read method in around 200-300 ms after start, after taking time to compile to machine code in memory. So I didn't optimize until there. Hence the reason why I let multiplications as is. However, after the first read, no instruction is superfluous.

I used a state machine to remove all the jumps, similar to Bubbler' submission, because if you thought that `if`s are slow, wait until you see `if`s in Java!

Also I optimized the reading and writing by creating my own non buffered streams (I used `new File{Input,Output}Stream(FileDescriptor.{in,out})` instead of the slower, buffered `System.{in,out}`).

Implementation note: if EOF is found before the expected trigger, it will crash.

But while I hope this code can compete, I wouldn't be surprised at all if it ends last.
> 7 votes

# Answer
# C (gcc)

```
#include <stdio.h>

int main() {

  FILE* const in = stdin;
  FILE* const out = stdout;
  char c = 0;

  #define is_or(t, l) \
    c = fgetc_unlocked(in); \
    if (__builtin_expect(c != t, 0)) goto l

  x:
  if (__builtin_expect(c == 'd', 1)) goto r;
  d:
  is_or('d', d);
  r:
  is_or('r', x);
  is_or('a', x);
  is_or('w', x);
  is_or('!', x);
  fwrite_unlocked("bang!\n", 1, 6, out);

  return 0;
}

```

Try it online!

`gcc -Ofast bang.c`

I have no idea of its performance. Just have a try...
> 6 votes

# Answer
# C (gcc)

```
#include <stdio.h>

int transition_table[128*6] = {
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,

    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 0,   640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 512, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,

    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 512, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 128, 640, 640, 640, 640, 640, 640, 640, 640,

    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 256, 640, 640, 512, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,

    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 512, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 384, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,

    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 512, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640,
    640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640
};

int main() {

  FILE* const in = stdin;
  FILE* const out = stdout;
  char c = 0;
  int state = 640;
  while(state) {
      c = fgetc_unlocked(in);
      state = transition_table[state + c];
  }
  fwrite_unlocked("bang!\n", 1, 6, out);

  return 0;
}

```

Try it online!

Throwing a hardcoded state transition table into the mix, in order to eliminate the jumps as much as possible. Honestly I don't know which optimization flag will give the best results. You could try `gcc -Ofast bang.c` or `gcc -O3 bang.c`. (maybe `-O2` too?)
> 6 votes

# Answer
# Rust

```
use std::hint::unreachable_unchecked;
use std::io::{stdin, stdout, Read, Write};
pub fn main() {
    let key = b"draw!";
    let temp = stdin();
    let mut stdin = temp.lock();
    let tmp = stdout();
    let mut out = tmp.lock();
    let mut i = 0;
    let mut buf = [0];
    loop {
        stdin
            .read(&mut buf)
            .unwrap_or_else(|_| unsafe { unreachable_unchecked() });
        let read = *unsafe { buf.get_unchecked(0) };
        if unsafe { read == *key.get_unchecked(i) } {
            i += 1;
        } else {
            i = (read == b'd') as usize;
        }
        if i == 5 {
            out.write(b"bang!")
                .unwrap_or_else(|_| unsafe { unreachable_unchecked() });
            out.flush()
                .unwrap_or_else(|_| unsafe { unreachable_unchecked() });
            break;
        }
    }
}

```

Try it online!

A solution in rust. It is pretty similar to @hyper-neutrino's solution, but it makes sure to flush the output buffer after writing and also asserts that io errors can't happen (it will be undefined behavior if they do, probably causing a sigill). Build `rustc -Copt-level=3 -Clto=fat -Ctarget-cpu=native -o main` and run `./main`
> 6 votes

# Answer
# C

```
#include "stdio.h"

int main() {
  int i = 0;
  while (1) {
    i ++;
  int c = getchar();
    switch (i) {
      case 1:
        if (c != 100) i = 0;
        continue;
      case 2:
        switch (c) {
          case 100:
            i = 1;
          case 114:
            continue;
          default:
            i = 0;
            continue;
        }
      case 3:
        switch (c) {
          case 100:
            i = 1;
          case 97:
            continue;
          default:
            i = 0;
            continue;
        }
      case 4:
        switch (c) {
          case 100:
            i = 1;
          case 119:
            continue;
          default:
            i = 0;
            continue;
        }
      case 5:
        switch (c) {
          case 100:
            i = 1;
          case 33:
            continue;
          default:
            i = 0;
            continue;
        }
      default:
        puts("bang!");
    }
    break;
  }
}

```

Compiled with `gcc -O3 -o foobar foobar.c`, run with `./foobar` (I'm on Windows, so the `-o` and `./foobar` is a guess).

A variation on hyper-neutrino's solution. Uses a switch statement instead of indexing into a string. Hopefully, this makes it faster.
> 5 votes

# Answer
# C (clang), 343 bytes

```
#include <stdio.h>

int main()
{
    const char draw[] = "draw!";
    size_t i = 0;
    while (i < 5)
    {
        char c = getchar_unlocked();
        i = c==draw[i] ? i + 1 : c=='d';
    }
    putchar_unlocked('b');
    putchar_unlocked('a');
    putchar_unlocked('n');
    putchar_unlocked('g');
    putchar_unlocked('!');

    return 0;
}

```

Try it online!

Compiled with `-Ofast`.
> 4 votes

# Answer
# C++ (gcc)

Probably not the fastest, but wanted to give it a try:

```
#include <iostream>

std::string a;

int main(){
    std::cin >> a;
    if(a == "draw!") std::cout << "bang!";
}

```

Compiled using `g++ -Ofast bang.cpp`.
> 3 votes

# Answer
Python:

```
from sys import stdin
def fgitw(func=stdin.readline, it=iter):
    for _ in it(func, 'draw!'):
        pass
    print("bang!")
fgitw()

```

A smaller version will be simply(but `sys.stdin.readline` with local variables above should be faster):

```
for _ in iter(input, 'draw!'):
    pass
print("bang!")

```
> 1 votes

# Answer
## C (GCC, Linux x86-64)

I have implemented the following ideas naively hoping for performance without testing:

* the translation `draw!` to `bang!` happens via a lookup table, i.e. without any jumps
* the write to stdout happens via a syscall to Linux' `write` (without any indirections of calling glibc's `write` wrapper)
* the program exits via a syscall to Linux' `exit` (without any indirections of calling glibc's `exit` wrapper)

You can see the generated asm on godbolt: https://godbolt.org/z/Ex3T5G5Gq. Compile with `gcc -O3 -march=x86-64 -fomit-frame-pointer draw-bang.c -o draw-bang`.

<pre><code>#include <stdio.h>
#include <unistd.h>
#include <asm/unistd.h>

static inline ssize_t my_write(int, const void*, size_t);
static inline void __attribute__((noreturn)) my_sys_exit(void);

/**
 * table[1 -- 128] translates ASCII characters with codepoint 0 -- 127
 * to other ASCII characters such that
 * 1. `draw!` translates to `bang!` and
 * 2. any other character translates to `\0`
 *
 * table[0] is `\0`.
 *
 * Rationale: `table + 1` can be indexed by the return value of `getc(stdin)`.
 *             And upon error or EOF, we nicely get `table[0]`, i.e. `\0`.
 */
static char table[129] = {
    '\0', // -1-th index
    // 128 entries follow
    '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', //   0 --   9
    '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', //  10 --  19
    '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', //  20 --  29
    '\0','\0','\0', '!','\0','\0','\0','\0','\0','\0', //  30 --  39
    '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', //  40 --  49
    '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', //  50 --  59
    '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', //  60 --  69
    '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', //  70 --  79
    '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', //  80 --  89
    '\0','\0','\0','\0','\0','\0','\0', 'n','\0','\0', //  90 --  99
     'b','\0','\0','\0','\0','\0','\0','\0','\0','\0', // 100 -- 109
    '\0','\0','\0','\0', 'a','\0','\0','\0','\0','g',  // 110 -- 119
    '\0','\0','\0','\0','\0','\0','\0','\0'            // 120 -- 127
};
static char out[6]; // to hold "bang!\0"

int main(void) {
    char c, i;
    while ((c = (table + 1)[getc(stdin)])) {
        out[i++] = c;
    }
    my_write(STDOUT_FILENO, out, sizeof(out));
    my_sys_exit();
}

/**
  * "Reimplementation" of write (2) function that GCC is happy to fully inline.
  *
  * Source: <https://stackoverflow.com/a/9508738/603003>
  * Author: Daniel Kamil Kozar <https://stackoverflow.com/users/1155000/daniel-kamil-kozar> and editors
  * License: CC BY-SA 4.0 <https://creativecommons.org/licenses/by-sa/4.0/>
  */
static inline ssize_t my_write(int fd, const void *buf, size_t size) {
    ssize_t ret;
    asm volatile
    (
        "syscall"
        : "=a" (ret)
        //                 EDI      RSI       RDX
        : "0"(__NR_write), "D"(fd), "S"(buf), "d"(size)
        : "rcx", "r11", "memory"
    );
    return ret;
}

/**
 * Exit the current thread (process for single-threaded processes) using the `exit` Linux
 * system call.
 *
 * This translates to exactly one asm instruction as opposed to calling the usual standard
 * libraries's exit() family of functions: see <https://stackoverflow.com/a/46903734/603003>.
 */
static inline void __attribute__((noreturn)) my_sys_exit(void) {
    asm("syscall" : : "r"(__NR_exit));
}
```
</code></pre>
> 1 votes

# Answer
# C++ (clang, Linux x86-64)

```
#include <bit>
#include <cstdint>
#include <tuple>

#include <unistd.h>
#include <asm/unistd.h>

static_assert(std::endian::native == std::endian::little);

using U64 = std::uint64_t;

inline void sys_write(int fd, void const* buf, std::size_t count)
{
    asm volatile("syscall"
        :
        : "a"(__NR_write), "D"(fd), "S"(buf), "d"(count)
        : "rcx", "r11", "memory");
}

inline ssize_t sys_read(int fd, void* buf, std::size_t count)
{
    ssize_t r;
    asm volatile("syscall"
        : "=a"(r)
        : "0"(__NR_read), "D"(fd), "S"(buf), "d"(count)
        : "rcx", "r11", "memory");
    return r;
}

U64 const DRAW = UINT64_C(0x2177617264);
U64 const MASK = UINT64_C(0xFFFFFFFFFF);

inline bool contains_it(U64 x)
{
    for(auto [pattern, mask] : {
        std::tuple{DRAW <<  0, MASK <<  0},
        std::tuple{DRAW <<  8, MASK <<  8},
        std::tuple{DRAW << 16, MASK << 16},
        std::tuple{DRAW << 24, MASK << 24}
    })
    {
        if((x & mask) == pattern) [[unlikely]]
        {
            return true;
        }
    }
    return false;
}

inline bool contains_it(U64 const* first, U64 const* last_incl)
{
    U64 prev = 0;
    for(auto p = first; p <= last_incl; ++p)
    {
        if(contains_it(*p) || contains_it((*p << 32) | (prev >> 32))) [[unlikely]]
        {
            return true;
        }
        prev = *p;
    }
    return false;
}

int main()
{
    std::uintptr_t const MAX_READ = 1'048'576;
    std::size_t const S = sizeof(U64);

    U64 u64s[1 + MAX_READ / S + 1] = {};

    int r = MAX_READ;

    while(1)
    {
        int rem = r % S;
        U64* end = u64s + 1 + r / S;
        *end &= ~(U64(-1) << (rem * 8));

        if(contains_it(u64s, end))
        {
            sys_write(STDOUT_FILENO, "bang!", 5);
            return 0;
        }

        u64s[0] = end[-1];
        u64s[1] = end[0];

        r = sys_read(STDIN_FILENO, reinterpret_cast<char *>(u64s + 1) + rem, MAX_READ) + rem;
    }
}

```

Compile with `clang++-12 -std=c++20 -Ofast -march=native -o drawbang drawbang.cpp`.

Clang’s optimizer is scarily efficient in how it vectorizes this code — godbolt. The entirety of the main loop is under `.LBB0_4`, where it takes as few as 16 instructions to go through 8 bytes. Some of those are conditional jumps, which shouldn’t matter as the CPU should predict the outcomes correctly, for which purpose the code starts by going through a megabyte of zeroes.

Like other submissions, the code assumes it will be fed junk that it has to ignore until it encounters the key string.
> 0 votes

---
Tags: fastest-code, restricted-time
---