title: "Hello, World!" (Cops' thread)

text:
# Question
Title: "Hello, World!" (Cops' thread)
*This is the cops' thread. The robbers' thread is here.*

Your challenge is to write a program or function that, with a certain input, prints the exact string `Hello, World!` and a newline. Capitalization, spacing and punctuation must be exact.

Input may be taken via standard input, a file, or command-line/function arguments. Output may be given via return value, writing to a file, or standard output.

Your program must print `Hello, World!` for at least one input. When your program is given the wrong input (i.e. the input that does not make it print `Hello, World!`), it can do whatever you like - crash, print random nonsense, call Chuck Norris, etc.

**You may not use a hashing algorithm or any similar methods of obscuring the required input.**

Submissions are preferred to be runnable & crackable on TIO. Submissions not runnable or crackable on TIO are allowed, but please include instructions to download / run them.

After one week, this challenge will be closed to future cop submissions. The winner is the shortest code that is uncracked after a week of posting it ("it" being the code, not this challenge). The winner will be accepted after two weeks.

After a week has passed since posting, please mark your answer as safe and show the input (in a `> ! spoiler quote`). If a robber cracks your submission (before the week ends), please mark it as cracked and show the halting input (in a `> ! spoiler quote`).

# Looking for uncracked submissions?

```
fetch("https://api.stackexchange.com/2.2/questions/137742/answers?order=desc&sort=activity&site=codegolf&filter=!.Fjs-H6J36vlFcdkRGfButLhYEngU&key=kAc8QIHB*IqJDUFcjEF1KA((&pagesize=100").then(x=>x.json()).then(data=>{var res = data.items.filter(i=>!i.body_markdown.toLowerCase().includes("cracked")).map(x=>{const matched = /^ ?##? ?(?:(?:(?:\[|<a href ?= ?".*?">)([^\]]+)(?:\]|<\/a>)(?:[\(\[][a-z0-9/:\.]+[\]\)])?)|([^, ]+)).*[^\d](\d+) ?\[?(?:(?:byte|block|codel)s?)(?:\](?:\(.+\))?)? ?(?:\(?(?!no[nt][ -]competing)\)?)?/gim.exec(x.body_markdown);if(!matched){return;}return {link: x.link, lang: matched[1] || matched[2], owner: x.owner}}).filter(Boolean).forEach(ans=>{var tr = document.createElement("tr");var add = (lang, link)=>{var td = document.createElement("td");var a = document.createElement("a");a.innerHTML = lang;a.href = link;td.appendChild(a);tr.appendChild(td);};add(ans.lang, ans.link);add(ans.owner.display_name, ans.owner.link);document.querySelector("tbody").appendChild(tr);});});
```

```
<html><body><h1>Uncracked Submissions</h1><table><thead><tr><th>Language</th><th>Author</th></tr></thead><tbody></tbody></table></body></html>
```

# Answer
> 3 votes
# Python 3, ~~191~~ 186 bytes (SAFE!)

Same as my previous answer, but without the noob eval statement, so that somebody actually has to solve the problem I created.

```
import sys
from numpy import *
e=enumerate
c='Hello, World!'
print(''.join([c[int(sum([c*cos(n*i)for i,c in e(fromiter(sys.argv[1:],float))])+.01)]for n in[2*i+ord(n)for i,n in e(c)]]))

```

now execute it with the correct parameters, such as `python3 hw.py 1 2 3`

---

*Edit*: previous version was missing a comma in "Hello, World!", and also I realized that it had an unnecesary ennumerate, which is now gone.

---

*Edit 2*: Just for fun, here is an almost identical Pyth version (47 bytes) of the same code:

```
KEJ"Hello, World!"jkm@J.Rs.e*b.t*dk1K0.e+*2kCbJ

```

Input is taken from `stdin` and is in the form of a list of arguments, such as `[1,2,3]`

I see no point in posting a separate answer because if you crack the Pthyon3 version, then you also crack the Pyth version, even without knowing Pyth.

---

Answer:

> python3 hw.py 10.72800138 13.23008796 19.30176276 16.13233012 18.10716041 0.98306644 8.18257475 19.20292132 10.99316856 -2.15745591 6.01351144 5.45443094 10.41260889

Explanation of code:

> `''.join()` creates the hello world string out of an array of characters from the string `"Hello, World!"`. The puzzle is solved when those indicies are `[0,1,2,3,4,5,6,7,8,9,10,11,12]`. Each index is calculated from an input and the constants given on the command line. The inputs are a hard coded series: `[2*i+ord(c) for i,c in enumerate('Hello, World!')]`. The funtion that relates the input, the constants, and the output (indicies) is this: `sum([c*cos(x*i) for i,c in enumerate(CONSTANTS)])`. This is a classic modelling problem, where you are trying to fit data to your model.

Arriving at the solution, in python:

> ```
> from scipy import optimize
> x = [2*i+ord(c) for i,c in eumerate('Hello, World!')]
> y = `[0,1,2,3,4,5,6,7,8,9,10,11,12]`.
> # make your function: 13 terms means we can achieve 13 exact outputs
> def f(x,a,b,c,d,e,f,g,h,i,j,k,l,m):
>     return sum([c*cos(x*i) for i,c in enumerate([a,b,c,d,e,f,g,h,i,j,k,l,m])])
> # curve fit
> ans,_ = optimize.curve_fit(f,x,y)
> # check answer
> [round(f(a,*ans),0) for a in x] # should be 0-12
> ```

# Answer
> 12 votes
# TeX - 38 bytes Cracked(ish)

This is worth a shot, because I can't imagine anyone on a site about writing short pieces of code would know TeX:

```
\read16to\x\message{Hello, World!}\bye

```

To run it, you should get a hold of some form of TeX that allows interactive mode. Save this to a file, and run TeX (or pdfTeX, XeTeX, etc.) on it.

Edit: I'm currently considering this semi-cracked. The intended solution uses input from stdin, but TeXnically input from the way the program is invoked is valid. I'll be adding more devious TeX answers if someone gets the intended method.

Here's the intended solution:

> ^C Ia - The first key is control-c, which causes an error. Then, you press I (capital i) to input a command. Then you type a (or anything else to be typeset). Normally, the message that was printed to stdout would be followed by a space and then a ')'. When you typeset something, it causes the font information to be output after the message. That means that a newline is thrown in, and the ')' gets moved later.

That may be underhanded, but should still be within the rules of the game.

# Answer
> 7 votes
# \>\<\>, 538 bytes, Cracked by rexroni

```
v
\">/v>v\v</>"
/!?lp%*2di%*2di
a
v   "        "       "
   "l"      "o"  /  "e"
v   "        "     " "
      "   /       "l"/
v    "!"           "
 //   " " "      \
v     \"d"o"   " "    "
      " " "   "o"r"  "!"
v"   "H"       " "    "
"l"   ""
""    "r" "         "
    \  " "l"       "d"  "
v   "     "      "  "  "H"
   "e"         /","     "
v " " "     "  " "
 "e" "W"  /"d""l"
v " " "     "  "      "
   "H"               "!"
v   "                 "
                        v
>>"Hello world?"       >o<
                        ^

```

Try it online, or you may want to use the fish playground.

The first three lines read in a string from STDIN and use its charcodes mod 26 as coordinates to put the characters "`>/v>v\v</>`" into the maze below. The intended solution is a 20-character string made of the letters A–Z only (although you're allowed to use anything you want, of course).

Solution:

> The intended input is `OCEANICWHITETIPSHARK` (it's a fish!). The path through the maze looks like:
>
> ```
> v
> \">/v>v\v</>"
> /!?lp%*2di%*2di
> a                |  |
> v   "        "   |  |"
> | v"l"______"o"__/  "e"
> v | "        "     " "
> | |   "   /       "l"/
> v |  "!"           "|
> |//   " " "    v_\  |
> v|    \"d"o"   " "  | "
> ||    " " "   "o"r" |"!"
> v"   "H"       " "  | "
> "l"___""_______ _/__/_____
> ""    "r" "    | |  "
> |>__\  " "l"   | | "d"  "
> v   "     "    | "  "  "H"
> |  "e"v________/"," |   "
> v " " "     "  " "  |
> |"e"|"W"  /"d""l"|  |
> v " " "     "  " |  | "
> <  "H">__________ __\"!"__
> v   "            |  | "
>     >____________ __ ___v
> >>"Hello world?" |  |  >o<
>                  |  |   ^
> ```

# Answer
> 6 votes
# Octave, 59 bytes, Cracked

This works in Octave 4.2.0. I can't guarantee compatibility with all versions.

```
i=input('');printf('%c',i*~all(isequal(i,'Hello, World!')))

```

Note: This doesn't print any trailing spaces or newlines. This is what it looks like:

It basically says: "Print the input string, unless the input is 'Hello, World!', in which case it should print nothing (or the null-character).

# Answer
> 5 votes
# CJam, 7 bytes (cracked)

```
q5/:i:c

```

Try it online!

Intended input:

> ```
> 65608656376564465644656476558065568656236564765650656446563665569
> ```

# Answer
> 5 votes
# Explode, 23 bytes, Cracked

```
@_?&4_-j>5&f^~c>&6\|4>7

```

More coming, this is just the beginning \>:)

**Try it online!**

## Explorer Explanation

There are four explorers in this program. I'm not entirely sure that wait (`>`) is working correctly.

```
@_?

```

Read user input (`?`), write and extend the tape (`@`) down (`_`).

```
&4_-j>5

```

For 4 ticks (`4`), modify the tape (`&`) downwards (`_`), jumping by 5 (`5`), by subtracting (`-`) 19 (`j`).

```
&f^~c>

```

For 16 ticks (`f`), modify the tape (`&`) upwards (`^`) in a wave (`~`), alternating no affect, +13, no affect, and -13 (`c`).

```
&6\|4>7

```

For 6 ticks (`6`), modify the tape (`&`) in both directions (`|`), decreasing (`\`) by 4 (`4`) each time, and jumping by 7 (`7`). Decreasing means that it subtracts 4 the first time, 8 the second time, etc.

# Answer
> 5 votes
# MATL, 6 bytes. Cracked

```
tsZp?x

```

Try it online!

# Answer
> 5 votes
# JavaScript (ES6), ~~173~~ ~~169~~ ~~163~~ ~~150~~ ~~151~~ ~~148~~ 143 bytes (Cracked)

Let's have something totally different... and *totally evil*.

```
const e=eval,p=''.split,c=''.slice,v=[].every,f=s=>(t=c.call(s),typeof s=='string'&&t.length<81&&v.call(p.call(t,`\n`),l=>l.length<3)&&e(t)(t))

```

Usage: `f(something) // returns 'Hello, World!'`

Try it online!

# Answer
> 4 votes
# C# (.NET Core), ~~130~~ 152 bytes, CRACKED

+22 bytes, I forgot about trailing newline... Program works the same as before, the newline is added to any output.

```
a=>a.Distinct().Select((x,y)=>a.Reverse().Skip(y).First()*x%255).Take(a.First()-33).Concat(new int[]{10}).Select(x=>(char)x).ToArray()

```

Try it online!

Byte count also includes

```
using System.Linq;

```

For a start I went for something not too crazy. It can has multiple answers.

The "official" crack:

> . !$0%\>5&8'#?)S\*TuE\[MRX\`+9

# Answer
> 4 votes
# tcc, 89 bytes, cracked by Dennis

```
#!/usr/bin/tcc -run
#include <stdio.h>

int main()
{
    puts("\n");
}
#include "/dev/stdin"

```

This is particularly evil due to tcc's dynamic resolution. Lots of functions are predeclared and trying to overwrite them simply doesn't work.

# Answer
> 4 votes
# Bash, 62 bytes, (cracked by ArchDelacy)

```
[[ ! "${1////x}" =~ [[:alnum:]] ]]&&[[ $# = 1 ]]&&bash -c "$1"

```

No alphanumerics or forward slashes. You should have fun with this one.

Try it online!

# Answer
> 4 votes
# brainfuck, 7 bytes cracked

```
,+[.,+]

```

Try it online!

Good luck. (doesn't work with every BF interpreter

# Answer
> 3 votes
# Cubically, 159 bytes (Cracked)

```
+53$!7@6:2/1+551$?7@6:5+52$!7@66:3/1+552$?7@6:5+3/1+4$!7@6:5/1+3$?7@6:5+1/1+54$!7@6:3/1+552$?7@6:5+1/1+552$?7@6:5+52$!7@6:1/1+551$?7@6:5+1/1+3$!7@6:1/1+1$(@6)7

```

This will be pretty easy to those who are comfortable with Cubically. Try it online!

# Answer
> 3 votes
# 6502 machine code (C64), 51 53 bytes (Cracked)

```
00 C0                     .WORD $C000     ; load address
20 FD AE                  JSR $AEFD
20 EB B7                  JSR $B7EB
8A                        TXA
0A                        ASL A
45 14                     EOR $14
8D 21 C0                  STA $C021
45 15                     EOR $15
85 15                     STA $15
49 E5                     EOR #$E5
85 14                     STA $14
8E 18 D0                  STX $D018
A0 00                     LDY #$00
B1 14                     LDA ($14),Y
20 D2 FF                  JSR $FFD2
C8                        INY
C0 0E                     CPY #$0E
D0 F6                     BNE *-8
60                        RTS
C8 45 4C 4C 4F 2C 20 D7   .BYTE "Hello, W"
4F 52 4C 44 21 0D         .BYTE "orld!", $D

```

### Online demo

**Usage**: `SYS49152,[x],[n]`, where `x` is a 16bit unsigned integer and `n` is an 8bit unsigned integer.

> Input is 52768 and 23 (SYS49152,52768,23)
> The second parameter is directly written to `D018`, a control register of the VIC-II graphics chip. Using a suitable reference, you can deduce what to write there for setting lowercase mode without changing other modes and the address of the screen memory: `$17`, or decimal `23`. With that, you can follow the arithmetics in the code, so the first parameter ends up with the correct string address in `$14/$15` (little-endian). A more in-depth explanation can be found in the crack.

Invoked with wrong values, a *crash* is **very likely**.

For cracking, you might want to run it in a local installation of vice, so here's a BASIC loader to paste into the emulator (`RUN` it to place the program at `$C000`):

```
0fOa=49152to49202:rEb:pOa,b:nE
1dA32,253,174,32,235,183,138,10,69,20,141,33,192,69,21,133,21,73,229,133,20,142
2dA24,208,160,0,177,20,32,210,255,200,192,255,208,246,96,200,69,76,76,79,44,32
3dA215,79,82,76,68,33,13

```

**Update:** Added two bytes for the load address to make this an executable C64 `PRG` file in response to the discussion on meta

# Answer
> 3 votes
# JavaScript (ES6), 102 bytes (Cracked)

The previous version has a massive cheese. Let's try this again...

```
f=s=>{let r='',i=0;while(i<13)r+=!s[i][0]||s[i]=='Hello, World!'[i]||s[i++];return r};Object.freeze(f)

```

Try it online!

Author solution:

> new Proxy({v:Array(13).fill(0)},{get:(o,p)=\>\['a','','Hello, World!'\[p\]\]\[o.v\[p\]++\]})

Usage:

> var p=new Proxy({v:Array(13).fill(0)},{get:(o,p)=\>\['a','','Hello, World!'\[p\]\]\[o.v\[p\]++\]}) console.log(f(p))

# Answer
> 2 votes
# Python 2, 63 bytes, cracked

Just to get the ball rolling...

```
#coding:rot13
cevag vachg()==h'Hello, World!'naq'Hello, World!'

```

Try it online!

# Answer
> 2 votes
# Pyth, 18 bytes (Cracked)

```
IqGQ"Hello, World!

```

This is extremely easy, and anyone that knows Pyth would crack it in the blink of an eye, but still... Note that you must put the String between quotes.

**Try it online!**

# Answer
> 2 votes
# JavaScript (Browser only), 95 bytes (Cracked)

```
try{a=JSON.parse(prompt());try{a=='[object Object]'}catch(a){alert('Hello, World!')}}catch(a){}

```

Not too hard. Has multiple solutions.

# Answer
> 2 votes
# Jelly, 11 bytes (cracked)

```
sLÆ½$Xṙ5O½Ọ

```

Try it online!

Intended input:

> ```
> 〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ
> ```

# Answer
> 2 votes
# 05AB1E, 20 bytes (Cracked)

Shouldn't be too hard though:

```
•GG∍Mñ¡÷dÖéZ•2ô¹βƵ6B

```

Uses the **05AB1E** encoding. Try it online!

# Answer
> 2 votes
# Jelly,  ~~20~~  21 bytes (Cracked)

+1 byte - "...and a trailing newline"

```
œ?“¥ĊɲṢŻ;^»œ?@€⁸ḊFmṪ⁷

```

**Try it online!**

There are, in fact, infinite solutions.

# Answer
> 2 votes
# Ly, 12 bytes (Cracked)

```
n[>n]<[8+o<]

```

Try it online!

~~I don't expect this to last very long, but oh well.~~ It didn't last very long.

# Answer
> 2 votes
# Lua 5.1, 44 bytes (Cracked)

```
s=...loadstring(#s>4+#s:gsub("%l","")or s)()

```

Note that Lua 5.1 is a different language than Lua 5.2 or Lua 5.3. "Try it online" doesn't have Lua 5.1. You can check your Lua version by running `print(_VERSION)`. (There should be a solution in any implementation that uses PUC-Rio's Lua 5.1 core.)

As a test harness, you can use something like this:

```
function test(...)s=...loadstring(#s>4+#s:gsub("%l","")or s)()end

test[[
This is my input!
It can have multiple lines!
]]

```

Test harness on repl.it

# Answer
> 2 votes
# Python3, 192 bytes Cracked I guess

```
from sys import *
from numpy import *
e=enumerate
c='Hello World!'
w=eval(argv[1])
x=[ord(n)+2*i for i,n in e(c)]
print(''.join([c[int(sum([c*cos(n*i)for i,c in e(w)])+.01)]for i,n in e(x)]))

```

The text it reads is the first program argument: `python3 hw.py '[1,2,3]'`

Don't be lame and try to put a `print("Hello World!")` statement as the argument... it prints an error afterwards anyways (at least on the command line), so I don't think that should count. (Edit: somebody did exactly that)

# Answer
> 2 votes
# C (GCC on TIO), 84 bytes golfed (Cracked)

```
#include<stdio.h>
main(x){scanf("%d",&x);printf("%2$s","Hello, World!\n",(void*)x);}

```

Here's an ungolfed version that works too:

```
#include <stdio.h>
int main(void)
{
    int x;
    scanf("%d",&x);

    printf("%2$s","Hello, World!\n",(void*)x);
}

```

# Answer
> 2 votes
# CJam, 130 bytes (safe)

```
q'p/{'s/{{"cjaei"#}%{)},{`}%S*}%']*}%'[*~]Y8#,:Y;0a\{{__a#{\{_T=}{1$E}w\;}{"T(:T; _T=co T)
:T)0e] _T=)Y=T\t _T=(Y=T\t"S/=~}?}/}:E~;

```

Try it online!

This is split across two lines for clarity; the newline is not included.

This is semi-golfed, which makes it that much harder to understand.

There are an infinite number of solutions here. If anybody wants to try and find one, I wish them good luck...

## Solution:

> `aipeepceeaiaeeeaeeeccsiiiiaesnccccjccccijcjjccejccccjaajaaaijcjeeejaajaijcccccej`

# Answer
> 2 votes
# JavaScript (ES6) 107 Bytes \[Thanks Евгений Новиков\] (Cracked)

```
i=r=>{for(e="",n=0;r.length>n;o=r.charCodeAt(++n),e+=String.fromCharCode(((3^o^19)<<1^15^13)<<1));return e}

```

Call on the `i` function using a string.

*The `console.log...` is for testing purposes.*

Try It Online!

# Answer
> 2 votes
# JavaScript (ES6), 92 bytes (Cracked)

This simple string copy function seems to be *really* resisting you to copy any strings resembling `Hello, World!`...

```
f=s=>{let r='',i=0;while(i<13)r+=s[i]=='Hello, World!'[i]||s[i++];return r};Object.freeze(f)

```

Try it online!

# Answer
> 2 votes
# Röda, 71 bytes (Cracked)

```
{[[head(_)]..[unpull(1)if[_1>1]]]|[_()|chars|unorderedCount|[_*(_-1)]]}

```

Try it online!

Usage: `push(/* input */) | f()` (where f is a variable that holds the function above).

# Answer
> 2 votes
# JavaScript (ES6), ~~135~~ 119 bytes, (Cracked)

```
const t='Hello, World!',g=q=>eval(`(function(p,q${q}){return eval(p),eval(q)})`),f=s=>g('')(s,0)==t&&g('=1')(s,0)!=t&&t

```

Try it online!

# Answer
> 2 votes
# Ruby, 88 bytes, Cracked by w0lf

```
require'prime'
n=gets.to_i
n.prime?&&$><<n.to_s(36)[0,5].capitalize
$><<", #$'"if/30191/

```

Try it online!

# Answer
> 1 votes
# C (gcc), 80 bytes, Cracked

```
#define O(c)(((char**)v)+c)
#define W(c)*(O(c)-**O(2)+x)
main(x,v){puts(W(42));}

```

Try it online!

Provide command line arguments for the desired output.

The intended input commandline was:

> "Hello, World!" ,

Quick explanation:

> The program does some pointer arithmetics on `argv[]`, using the first `char` of the second argument and the argument count. See the robbers' post for a full explanation. There are other solutions possible, but the one over there is the most simple one.

**Important**: This won't work when e.g. built for `amd64`, therefore the compiler switch `-m32` on tio.

# Answer
> 1 votes
# Perl 5, 23 bytes (Cracked)

```
eval<>;END{print$x='x'}

```

Usage: takes one line of input of stdin and evals it. The END block keeps simple attempts like `print"Hello, World!\n";exit` from working.

Try it Online!

> our $x;package X;require Tie::Scalar;@ISA=qw(Tie::Scalar);sub TIESCALAR{my$v;return bless\\$v,'X';}sub STORE{}sub FETCH{return "Hello, World!\n"}tie $x,'X';

# Answer
> 1 votes
# 6502 machine code (C64), 94 bytes (Cracked)

```
00 C0 20 FD AE 20 9E AD 20 A3 B6 A0 00 B9 25 C0 C0 01 F0 21 C0 07 F0 1D C0 0B
F0 19 20 20 C0 C8 D0 EB 51 22 4C D2 FF F0 48 FA A2 1C 6D 72 30 06 A9 03 48 7C
A3 8D 48 C0 B9 26 C0 8D 45 C0 B9 27 C0 8D 46 C0 A2 00 BD FD AE 49 23 20 20 C0
C8 E8 E0 03 D0 F2 C0 0E D0 B5 49 1A 8D 18 D0 60

```

Disassembled:

```
00 C0       .WORD $C000       ; load address
20 FD AE    JSR $AEFD
20 9E AD    JSR $AD9E
20 A3 B6    JSR $B6A3
A0 00       LDY #$00
B9 25 C0    LDA $C025,Y
C0 01       CPY #$01
F0 21       BEQ $C033
C0 07       CPY #$07
F0 1D       BEQ $C033
C0 0B       CPY #$0B
F0 19       BEQ $C033
20 20 C0    JSR $C020
C8          INY
D0 EB       BNE $C00B
51 22       EOR ($22),Y
4C D2 FF    JMP $FFD2
F0 48       BEQ $C06F
FA          .BYTE $FA
A2 1C       LDX #$1C
6D 72 30    ADC $3072
06 A9       ASL $A9
03          .BYTE $03
48          PHA
7C A3       .WORD $A37C
8D 48 C0    STA $C048
B9 26 C0    LDA $C026,Y
8D 45 C0    STA $C045
B9 27 C0    LDA $C027,Y
8D 46 C0    STA $C046
A2 00       LDX #$00
BD FD AE    LDA $AEFD,X
49 23       EOR #$23
20 20 C0    JSR $C020
C8          INY
E8          INX
E0 03       CPX #$03
D0 F2       BNE $C044
C0 0E       CPY #$0E
D0 B5       BNE $C00B
49 1A       EOR #$1A
8D 18 D0    STA $D018
60          RTS

```

### Online demo

**Important**: When load from disk (like in this online demo), the program only works after issuing a `NEW` command! Without first doing `NEW`, you'd only ever get an `?OUT OF MEMORY ERROR` when trying to pass a string.

---

**Usage:** `SYS49152,"[string]"`, where `[string]` is your input string.

Yes, input is a **string** this time, and the white area in the screenshot below doesn't tell you anything about the required length.

This should be quite hard to crack, but it's possible calculating everything back, no hashes or similar involved ;) You *might* need some reference for the C64 ROMs though. Further tip: look for an area only containing *data* in the disassembly listing :)

Like with my previous entry, here's a BASIC loader to paste into vice, just `RUN` this and the program is placed at `$C000`:

```
0fOa=49152to49243:rEb:pOa,b:nE
1dA32,253,174,32,158,173,32,163,182,160,0,185,37,192,192,1,240,33,192,7,240,29
2dA192,11,240,25,32,32,192,200,208,235,81,34,76,210,255,240,72,250,162,28,109
3dA114,48,6,169,3,72,124,163,141,72,192,185,38,192,141,69,192,185,39,192,141,70
4dA192,162,0,189,253,174,73,35,32,32,192,200,232,224,3,208,242,192,14,208,181
5dA73,26,141,24,208,96

```

**Solution**:

> 8bitsareenough

**Explanation**:

> The code basically uses an XOR key of the same length as `Hello, World!\n`. As this would be quite simple to crack, the key isn't placed in the code *as is* but there are 3 times 3 bytes that are calculated from the C64's ROMs.
> The 3 times 3 bytes in the data are in the format `<key>, <low>, <high>`, where `<low>, <high>` is the start address of 3 bytes in the ROM that are taken as part of our XOR key after XOR'ing them with `<key>`.
> It's possible to crack it with some reference / disassembly to the C64 ROMs. Of course, it's easier to just try and get the key from the running program. I attempted to prevent the easiest method of doing this (just entering `"Hello, World!\n"`, as XOR is reversed with the same key) by forcing a crash on wrong input. The crack linked cleverly modified the program, so it won't crash.
> Another nice possibility to crack this would have been to spot the single place where output happens: `EOR ($22),Y; JMP $FFD2`. If you know that fetching a string using the BASIC routines will place a pointer to that string in `$22/$23`, all you have to do is set a breakpoint at `EOR ($22),Y` and get the XOR key delivered in the accumulator byte by byte.

# Answer
> 0 votes
# PHP, 94 bytes, Cracked

```
<?=constant(explode(',',$argv[1])[0]."::".explode(',',$argv[1])[1])==262144?"Hello, world
":a;

```

Try it online! First codegolf submission, feel free to help me improve this

Cracked, intended input :

> ReflectionFunction,IS\_DEPRECATED

Because

> ReflectionFunction::IS\_DEPRECATED = 262144

---
Tags: code-golf, cops-and-robbers, hello-world
---


title: The Original Number

text:
# Question
Title: The Original Number
# Guidelines

## Scenario

John has an important number, and he doesn't want others to see it.

He decided to encrypt the number, using the following steps:

His number is always a non-decreasing sequence (ie. `"1123"`)

He converted each digit into English words. (ie. `"123" -> "ONETWOTHREE"`)

And then, rearrange the letters randomly. (ie. `"ONETWOTHREE" -> "ENOWTOHEETR"`)

John felt that his number were safe in doing so. In fact, such encryption can be easily decrypted :(

---

## Task

Given the encrypted string s, your task is to decrypt it and return the original number.

---

## Rules

* This is code golf, so the shortest answer in bytes wins
* You can assume that the input string is always valid
* The input string only contains uppercase letters
* The original numbers are always arranged in ascending order
* You may return the number in string or integer format
* The letters will only be shuffled between one word, not between the whole string.
* The numbers will only be from 1 to 9 inclusive (`ONE` to `NINE`)

---

## Possible Unscrambled String

Here is a list of the strings just after they have been converted to strings from the numbers:

```
 1 -> ONE
 2 -> TWO
 3 -> THREE
 4 -> FOUR
 5 -> FIVE
 6 -> SIX
 7 -> SEVEN
 8 -> EIGHT
 9 -> NINE

```

---

## Examples

`"NEO" -> 1`

`"ENOWOT" -> 12`

`"EONOTWHTERE" -> 123`

`"SNVEEGHEITNEIN" -> 789`

`"ENOOWTEERHTRUOFEVIFXISNEVESTHGIEENIN" -> 123456789`

`"NOEWOTTOWHEERT" -> 1223`

# Answer
# Jelly,  ~~38~~  37 bytes

```
ḟ“RGS”O“OX‘,“¢©“¢¢¤‘yF×4/%74ị⁽G×œ?9¤Ḍ

```

A monadic link taking a list of characters (the string) and returning an integer.

**Try it online!**

Uses a **very different** method to Pietu1998's Jelly answer, ~~yet has the same byte count~~ (~~I really thought it might~~ *it did* end up as less)!

Does not rely on the monotonicity of the original number (so an input of `HTREEWTONOE` would work for example).

### How?

First note that the words themselves (and therefore any anagrams thereof) can all be changed to ones of length 4 by removing any Rs, Gs and Ss and replacing any Os with two characters (say "12") and any Xs with three characters (say "345").

```
letters  -> -RGS  -> O:12, X:345
ONE         ONE      12NE
TWO         TWO      TW12
THREE       THEE     THEE
FOUR        FOU      F12U
FIVE        FIVE     FIVE
SIX         IX       I345
SEVEN       EVEN     EVEN
EIGHT       EIHT     EIHT
NINE        NINE     NINE

```

We may then map the product of the ordinals of those characters to the numbers 1 to 9 using modulo arithmetic, depending upon our choice (the "12345"), then look these up in a reordered list of the digits. The code actually casts to characters first and then replaces the ordinals, but it is also possible in 37 bytes with characters, e.g. "DIAAE" (try it).

```
ḟ“RGS”O“OX‘,“¢©“¢¢¤‘yF×4/%74ị⁽G×œ?9¤Ḍ - link: list of characters
 “RGS”                                - literal ['R','G','S']
ḟ                                     - filter discard
      O                               - convert to ordinals
       “OX‘                           - code-page indices list = [79,88]
            “¢©“¢¢¤‘                  - code-page indices lists = [[1,6],[1,1,3]]
           ,                          - pair -> [[79,88],[[1,6],[1,1,3]]]
                    y                 - translate (replace 79s (Os) with [1,6]
                                                       and 88s (Xs) with [1,1,3])
                     F                - flatten into a single list
                       4/             - 4-wise reduce by:
                      ×               -   multiplication (product of each window of four)
                         %74          - modulo 74
                                   ¤  - nilad followed by link(s) as a nilad:
                             ⁽G×      -   base 250 literal = 18768
                                œ?9   -   permutation of [1,2,3,4,5,6,7,8,9] at that
                                      -   index in a lexicographically sorted list of
                                      -   all such permutations -> [1,5,8,2,4,9,7,6,3]
                            ị         - index into
                                    Ḍ - convert from decimal digits to an integer

```

---

### Another 37

```
42BĖZ“Øȧɲ“Pt’żḥ€⁸*/)⁸xO×⁵/%⁽R1%⁽©v%⁵Ḍ

```

Try it online!

This one repeats characters such that any\* shuffled number name becomes length ten:

| characters | repeat |
| --- | --- |
| G R S T U V | 1 |
| H N | 2 |
| E F I | 3 |
| W | 4 |
| O | 5 |
| X | 6 |

e.g:

```
ONE    => OOOOONNEEE
TWO    => TWWWWOOOOO
THREE  => THHREEEEEE
OURF   => OOOOOURFFF
EVIF   => EEEVIIIFFF
IXS    => IIIXXXXXXS
VENES  => VEEENNEEES
GHIET  => GHHIIIEEET
NINE   => NNIIINNEEE
WOTISX => WWWWOOOOOTIIISXXXXXX

```

Then takes the products of the ordinals of length ten slices and performs a modulo chain to map these to \\$\[1,9\]\\$ appropriately.

<sup>* The repetition part works for "ZERO" too -\> "ZEEEROOOOO" as 'Z' will also repeat once.</sup>
> 7 votes

# Answer
# Python 2, ~~121~~ ~~117~~ 115 bytes

```
def g(s,a=0,f=''):
 for c in s:
    a+=34**ord(c)%43;r='P!\x83u\x8eI\x92|Z'.find(chr(a))+1
    if r:f,a=f+`r`,0
 return f

```

-4 bytes: After all that golfing I forgot to inline a single-use variable. Brain fart.
-2 bytes: Double-spaced indent → single tab indent (thanks to Coty Johnathan Saxman); note that this does not display correctly in the answer.

## Ungolfed (compatible with python 3):

```
nums = [80, 33, 131, 117, 142, 73, 146, 124, 90]

def decode(str):
    acc = 0
    final = ''
    for c in str:
        acc += (34**ord(c))%43
        if acc in nums:
            final += str(1+nums.index(acc))
            acc=0
    return final

```

## Magic number finder:

```
#!/usr/bin/env python3
from itertools import count, permutations

def cumul(x):
    s = 0
    for v in x:
        s += v
        yield s

all_words = 'ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE'.split()

for modulo in range(1, 1000):
    for power in range(1, 300):
        combinations = []
        for word in all_words:
            my_combination = []
            for perm in permutations(word):
                my_combination += cumul(power**(ord(x)) % modulo for x in perm)
            combinations.append(my_combination)

        past_combinations = set(())
        past_intermediates = set(())
        collision = False
        for combination in combinations:
            final = combination[-1]
            if final in past_intermediates or any(intermediate in past_combinations for intermediate in combination):
                collision = True
                break
            past_combinations.add(final)
            past_intermediates.update(combination)

        if not collision:
            print("Good params:", power, modulo)
            print("Results:", ", ".join(str(x[-1]) for x in combinations))

```

## Explanation:

I had a feeling that I could smash the ASCII bits together and sum them up somehow to determine when I had a full word. Originally I tried messing with `3**ord(letter)` and comparing to expected results, but it resulted in some very large numbers. I though it would be appropriate to brute-force some parameters a little, namely modulus (to ensure the numbers are small) and a multiplier to disperse the numbers differently around the range of the modulus.

I ended up changing the multiplier variable into a variable affecting the power itself because (from trial and error) that somehow managed to give me a slightly shorter golfed answer.

And above you see the results of that brute-forcing and a little manual golfing.

The reason for choosing `3**x` originally is because I knew you could represent every number there. The most repeated digits any number had is two (thrEE, sEvEn, NiNe, etc), so I decided to think of every input as a base-3 number. That way I could (mentally) represent them as something like `10100000000010020000` (three; a 1 in the `t` slot, a 1 in the `r` slot, a 1 in the `h` slot, and a 2 in the `e` slot). Each number this way gets a unique representation which can be easily pieced together by iterating the string and summing some numbers, and it ends up independent of the actual order of the letters. Of course, this didn't turn out to be the ideal solution, but the current solution is still written with this idea in mind.
> 10 votes

# Answer
# Python 2,~~131~~ 127 bytes

```
s=input()
for y in'WXGURFSOIZ':vars()[y]=s.count(y)
while Z<9:s+=[O-U-W,W,R-U,U,F-U,X,S-X,G,I-X-G-F+U][Z]*str(Z+1);Z+=1
print s

```

Try it online!

Based on a corrected version of the JavaScript Draco18s solution.
> 6 votes

# Answer
# C# (.NET Core), 234 bytes

```
string q(string s){string[]n="ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE".Split(',');var r="";int x=0,i=0,j;try{for(;;)for (j=x;;)if(n[i].IndexOf(s[j])>=0){if(++j==n[i].Length+x){r+=i+1;x=j;break;}}else{i++;break;}}catch{}return r;}

```

Try it online!

Expanded version:

```
static string q(string s)
{
    string[] n = "ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE".Split(',');
    var r = "";
    int x = 0, i = 0, j = 0;
    try
    {
        for(;;)
            for (j = x; ;)
                if (n[i].IndexOf(s[j]) >= 0)
                {
                    if (++j == n[i].Length + x)
                    {
                        r += i + 1; x = j;
                        break;
                    }
                }
                else
                {
                    i++;
                    break;
                }
    }
    catch { }
    return r;
}

```

Being my first entry, I'm uncertain about the rules... I'm only counting the size of the class used to de-crypt, not the code that tests it, right?

**Edit**

And for the fun of it - here's what I started doing, not reading the complete rules :S - See it at IdeOne. It de-crypts even when characters from one digit can be scrambled to any place in the string.

**Edit 2**

Shortened according to tips by TheLethalCoder. Thanks!

**Edit 3**

And now Titus shaved of a few more bytes. Thanks!

**Edit 4** Six years later :D

As Magic Octopus Urn commented, this wasn't working in all cases. Had to add a few bytes to make it work :(

Using try/catch I can ignore boundary checks and save a few bytes :P
> 5 votes

# Answer
# PHP, 164 bytes

```
for($c=count_chars($argn);$i<9;)echo str_pad("",[$c[79]-$c[87]-$u=$c[85],$c[87],$c[72]-$g=$c[71],$u,$f=$c[70]-$u,$x=$c[88],$c[86]-$f,$g,$c[73]-$x-$f-$g][+$i],++$i);

```

Try it online!

# PHP, 179 bytes

based on the previous approach check first the even numbers and then the odd numbers in increasing order

```
for($z=[$o=($c=count_chars($argn))[87],$f=$c[85],$x=$c[88],$g=$c[71],$c[79]-$o-$f,$c[72]-$g,$v=$c[70]-$f,$c[86]-$v,$c[73]-$x-$v-$g];$i<9;)echo str_repeat(++$i,$z[_405162738[$i]]);

```

Try it online!

# PHP, 201 bytes

```
for(;$o=ord(WUXGOHFVN[$i]);$i++)for(;$r[$o]<count_chars($argn)[$o];$t[]=$i>3?2*$i-7:2+2*$i,sort($t))for(++$r[$o],$n=0;$q=ord(([TO,ORF,IS,HEIT,EN,TREE,IVE,SEEN,NIE][+$i])[$n++]);)$r[$q]++;echo join($t);

```

Try it online!
> 5 votes

# Answer
# Javascript (ES6), ~~288~~ ~~150~~ 144 bytes

```
q=s=>[u=(l=t=>s.split(t).length-1)`U`,l`O`-l`W`-u,l`W`,l`R`-w,u,f=l`F`-u,x=l`X`,l`S`-x,g=l`G`,l`I`-x-g-f].map((n,i)=>`${i}`.repeat(i&&n)).join``

const testCases = ['NEO', 'ENOWOT', 'EONOTWHTERE', 'SNVEEGHEITNEIN', 'ENOOWTEERHTRUOFEVIFXISNEVESTHGIEENIN']

testCases.forEach(testCase => console.log(testCase, q(testCase)))
```

Longer than ~~the other two~~ one of the other JS entries, but I thought I'd drop an interesting approach that might work for someone in another language.

Essentially we can determine the following:

```
W -> 2
X -> 6
G -> 8
U -> 4

```

Any occurrence of these letters implies that that digit exists in the original number. From here we can deduce the rest of the digits:

```
R-U -> 3
F-U -> 5
S-X -> 7

```

Including the two complicated cases:

```
O-(U+W) -> 1
I-(X+G+(F-U)) -> 9

```

Both `1` and `9` area Hard comparatively. For ONE, `E` shows up more than once in some words (`SEVEN` has two) as does `N` (`NINE`), so we're stuck with checking for `O` which occurs in two other places, fortunately both are simple.

For NINE, nine is hard no matter how you slice it.

Thus we end up with this map:

```
[u=(l=t=>s.split(t).length-1)`U`,  //unused 0; precompute 'U's
 l`O`-l`W`-u,    //1
 l`W`,           //2
 l`R`-w,         //3
 u,              //4
 f=l`F`-u,       //5
 x=l`X`,         //6
 l`S`-x,         //7
 g=l`G`,         //8
 l`I`-x-g-f]     //9

```

9 is able to back-reference siX, eiGht, and Five (with 5 back-referencing foUr) with the variable assignments, saving bytes. Thanks to Neil for this, it uses several features of JS I am very unfamiliar with (the back-ticks for stripping `('` in half, for instance) and actually comes much closer to the idea I'd doodled out on paper before attempting to code it (I'd left 9 as "what's left over", thinking about it as "if I see an `X` I can remove it and an `S` and `I` from the string, then..." so that after the four simple cases the next 3 would *become* simple).

The reason this entry is *interesting* is because it can handle *any shuffled string* as input. i.e. rather than the individual words being shuffled, we can shuffle the whole string, which is what I thought John was doing originally:

```
q=s=>[u=(l=t=>s.split(t).length-1)`U`,l`O`-l`W`-u,l`W`,l`R`-w,u,f=l`F`-u,x=l`X`,l`S`-x,g=l`G`,l`I`-x-g-f].map((n,i)=>`${i}`.repeat(i&&n)).join``

const testCases = ['XENSENINEVSI']

testCases.forEach(testCase => console.log(testCase, q(testCase)))
```
> 5 votes

# Answer
# Mathematica, 133 bytes

```
(s={};c=Characters;j=c@#;Table[If[FreeQ[j~Count~#&/@c[#[[i]]]&@ToUpperCase@IntegerName@Range@9,0],s~AppendTo~i],{i,9}];FromDigits@s)&

```

**input**

> "VENESGTHIEENNI"

**output**

> 789
> 4 votes

# Answer
# Retina, 88 bytes

```
[EFIST]

^(ON|NO)*
$#1$*1
O

W
2
HR|RH
3
UR|RU
4
X
6
GH|HG
8
(NN)*$
$#1$*9
r`NV|VN
7
V
5

```

Try it online!

**Explanation**

* First, drop a bunch of unnecessary characters not needed for distinctness
* Pick the 1s off the front (this lets us drop the rest of the Os immediately after and clears up some Ns before we get to the 5, 7, 9 mess)
* 2, 3, 4, 6, and 8 are now trivial
* 9s are a double NN, so grab those off the end before we deal with 5 and 7
* Replace 7s from the right (so we don't reduce VNV to 75 instead of 57)
* 5s are the remaining Vs
> 4 votes

# Answer
# JavaScript (ES6), ~~142~~ 139 Bytes

Saved 3 Bytes thanks to Neil.

Doesn't currently take advantage of numbers are always arranged in ascending order

```
f=s=>s?'ENO|OTW|EEHRT|FORU|EFIV|ISX|EENSV|EGHIT|EINN'.split`|`.findIndex(w=>[...s.slice(0,y=w.length)].sort().join``==w)+1+f(s.slice(y)):''

```

```
f=s=>s?'ENO|OTW|EEHRT|FORU|EFIV|ISX|EENSV|EGHIT|EINN'.split`|`.findIndex(w=>[...s.slice(0,y=w.length)].sort().join``==w)+1+f(s.slice(y)):''

const testCases = ['NEO', 'ENOWOT', 'EONOTWHTERE', 'SNVEEGHEITNEIN', 'ENOOWTEERHTRUOFEVIFXISNEVESTHGIEENIN']

testCases.forEach(testCase => console.log(testCase, f(testCase)))
```
> 3 votes

# Answer
# Jelly, 38 bytes

```
Dị“©ȯ¿w¶&ÇhṆỌƘ#Ȯʋ~¢CNẓ_»Ḳ¤FṢŒu
L3*Ç€iṢ

```

Try it online!

### Explanation

```
L3*Ç€iṢ    Main link. Argument: s (string)
L            Get length of s.
 3*          Raise 3 to that power. This will always be greater than n.
   Ç€        Get the name of each of the numbers using the helper link.
     iṢ      Find the position of the sorted input.

Dị“©ȯ¿w¶&ÇhṆỌƘ#Ȯʋ~¢CNẓ_»Ḳ¤FṢŒu    Helper link. Argument: n (number)
D                                   Get digits of n.
  “©ȯ¿w¶&ÇhṆỌƘ#Ȯʋ~¢CNẓ_»            The string "one two (...) eight nine AA".
                        Ḳ           Split that string at spaces.
 ị                                  Get name of each digit in the list.
                          F         Flatten to a single string.
                           Ṣ        Sort the characters.
                            Œu      Make uppercase.

```
> 2 votes

# Answer
# Javascript (ES6), 221 bytes

```
s=>(m=btoa`8Ñ>Mc¾LtDáNQ!Q>HþHA7átþ4Ò`.split`+`.map(s=>RegExp(s.replace(/(.)\1*/g,c=>`(?=(.*${c[0]}){${c.length}})`))),t=0,r=0,[...s].map(c=>(t+=c,d=1,n=0,m.map((r,i)=>t.match(r)&&(d--,n=i)),d||(r=r*10+n+1,t=0))),r)

```

Example code snippet:

```
f=

s=>(m=btoa`8Ñ>Mc¾LtDáNQ!Q>HþHA7átþ4Ò`.split`+`.map(s=>RegExp(s.replace(/(.)\1*/g,c=>`(?=(.*${c[0]}){${c.length}})`))),t=0,r=0,[...s].map(c=>(t+=c,d=1,n=0,m.map((r,i)=>t.match(r)&&(d--,n=i)),d||(r=r*10+n+1,t=0))),r)

console.log(f("NEO"))
console.log(f("ENOWOT"))
console.log(f("EONOTWHTERE"))
console.log(f("SNVEEGHEITNEIN"))
console.log(f("ENOOWTEERHTRUOFEVIFXISNEVESTHGIEENIN"))
```
> 2 votes

# Answer
# Retina, 160 bytes

```
([ONE]{3})*([TWO]{3})*([THRE]{5})*([FOUR]{4})*([FIVE]{4})*([SIX]{3})*([SEVN]{5})*([EIGHT]{5})*([NIE]{4})*
$#1$*1$#2$*2$#3$*3$#4$*4$#5$*5$#6$*6$#7$*7$#8$*8$#9$*9

```

Try it online! Loosely based on @TessellatingHeckler's PowerShell answer.
> 2 votes

# Answer
# Perl 5, 102 + 1 (-n) = 103 bytes

```
for$i(map{"[$_]{".length.'}'}ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE){$,++;print$,while(s/^$i//)}

```

Try it online!
> 2 votes

# Answer
## C++, ~~296~~, 288 bytes

Short Version:

```
#define T string
using namespace std;T N[]={"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};T Q(T S){T R="";for(int i=0;i<9;i++){do{if(S.find(N[i])!=T::npos){S.erase(S.find(N[i]),N[i].size());R+=to_string(i+1);}}while(next_permutation(N[i].begin(),N[i].end()));}return R;}

```

Full Version:

```
#define T string
using namespace std;

T N[]={"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};

T Q(T S)
{
    T R="";
    for(int i=0;i<9;i++)                             //for all possible
                                                     //codewords (ONE,TWO...NINE)
    {
        do
        {
            if(S.find(N[i])!=T::npos)                //if found in encrypted word
            {
                S.erase(S.find(N[i]),N[i].size());  //erase it from the word
                R+=to_string(i+1);                  //save integer to the result string
            }
                                                    //check next permuation of codeword

        } while(next_permutation(N[i].begin(),N[i].end()));
    }

    return R;
}

```

Try ONLINE!

**Edit:**
1) 200-\>296 bytes, for including namespace and definition of N in the count, as suggested by orlp 2) 296-\>288, for using macro, thanks to Zacharý
> 1 votes

# Answer
# PowerShell, 182 bytes

```
[regex]::Replace("$args",'(?<1>[ONE]{3z2>[TWO]{3z3>[THRE]{5z4>[FOUR]{4z5>[FIVE]{4z6>[SIX]{3z7>[SVEN]{5z8>[EIGHT]{5z9>[NIE]{4})'.replace('z','})|(?<'),{$args.groups.captures[1].name})

```

Try it online!

Ungolfed but not working code:

```
[System.Text.RegularExpressions.Regex]::Replace("$args",

    '(?<1>[ONE]{3})
    |(?<2>[TWO]{3})
    |(?<3>[THRE]{5})
    |(?<4>[FOUR]{4})
    |(?<5>[FIVE]{4})
    |(?<6>[SIX]{3})
    |(?<7>[SVEN]{5})
    |(?<8>[EIGHT]{5})
    |(?<9>[NIE]{4})'

    ,{$args.groups.captures[1].name}
)

```

e.g. `(?<3>[THRE]{5})` matches the character class `THRE`, so it can match them out of order, and has to match any of these characters five times next to each other, and the capture group is named '3' to map names with numbers.

Rudimentary compression by swapping the repeating text `})|(?<` for a `z`.
> 1 votes

# Answer
# Ruby, ~~138~~ ~~114~~ 110 bytes

```
gsub(/#{"3ONE3TWO5THRE4FOUR4FIVE3SIX5SEVN5EIGHT4NIE".gsub(/(.)(\D+)/,'([\2]{\1})|')}/){(1..9).find{|i|$~[i]}}

```

Byte count includes 1 byte for the `-p` option.

### What?

This:

```
/#{"3ONE3TWO5THRE4FOUR4FIVE3SIX5SEVN5EIGHT4NIE".gsub(/(.)(\D+)/,'([\2]{\1})|')}/

```

is a regex literal which, through string interpolation, evaluates to:

```
/([ONE]{3})|([TWO]{3})|([THRE]{5})|([FOUR]{4})|([FIVE]{4})|([SIX]{3})|([SEVN]{5})|([EIGHT]{5})|([NIE]{4})|/

```

If we assign that to `regex`, the rest of the code is somewhat easy to grasp: Each match in the input is substituted with the number of the capturing group, extracted from the magical variable `$~` which contains the current match data:

```
gsub(regex){(1..9).find{|i|$~[i]}}

```

Try it online!
> 1 votes

# Answer
# Java 8, ~~198~~ 256 bytes

```
s->{String r="",x=r;for(String n:"ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE".split(" ")){for(char c:n.toCharArray())x+="(?=.*"+c+")";x+="["+n+"]{"+n.length()+"}x";}for(int i=0,q;i<9;)for(q=(s+" ").split(x.split("x")[i++]).length-1;q-->0;)r+=i;return r;}

```

+58 bytes.. due to regex of the previous version not working properly (it was also matching "EEE";"EEN";etc.)

**Explanation:**

Try it here.

```
s->{                     // Method with String as parameter and return-type
  String r="",           //  Result-String
         x=r;            //  Regex-String
  for(String n:"ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE".split(" ")){
                         //  Loop (1) from "ONE" through "NINE":
    for(char c:n.toCharArray())
                         //   Inner loop (2) over the characters of this String
      x+="(?=.*"+c+")";  //    Append regex-group `(?=\w*c)` where `c` is the capital character
                         //   End of inner loop (2) (implicit / single-line body)
    x+="["+n+"]{"+n.length()+"}x";
                         //   Append regex part `[s]{n}` where `s` is the String, and `n` is the length
  }                      //  End of loop (1)
  // The regex now looks like this, which we can split on "x":
  // (?=.*O)(?=.*N)(?=.*E)[ONE]{3}x(?=.*T)(?=.*W)(?=.*O)[TWO]{3}x(?=.*T)(?=.*H)(?=.*R)(?=.*E)(?=.*E)[THREE]{5}x(?=.*F)(?=.*O)(?=.*U)(?=.*R)[FOUR]{4}x(?=.*F)(?=.*I)(?=.*V)(?=.*E)[FIVE]{4}x(?=.*S)(?=.*I)(?=.*X)[SIX]{3}x(?=.*S)(?=.*E)(?=.*V)(?=.*E)(?=.*N)[SEVEN]{5}x(?=.*E)(?=.*I)(?=.*G)(?=.*H)(?=.*T)[EIGHT]{5}x(?=.*N)(?=.*I)(?=.*N)(?=.*E)[NINE]{4}x
  for(int i=0,q;i<9;)    //  Loop (3) from 0 through 9 (exclusive)
    for(q=(s+" ").split(x.split("x")[i++]).length-1;
                         //   Split the input on the current regex-part,
                         //   and save the length - 1 in `q`
        q-->0;           //   Inner loop (4) over `q`
      r+=i               //    And append the result-String with the current index (+1)
    );                   //   End of inner loop (4)
                         //  End of loop (3) (implicit / single-line body)
  return r;              //  Return the result-String
}                        // End of method

```
> 1 votes

# Answer
# Java (OpenJDK 8), 181 bytes

```
s->{String x="",r;for(int i=0,l;i<9;)for(r="ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE".split(",")[i++],l=r.length();s.matches("["+r+"]{"+l+"}.*");s=s.substring(l))x+=i;return x;}

```

Try it online!

I took the liberty to reuse Kevin Cruyssen's TIO template. Hope you don't mind ;)
> 1 votes

# Answer
# 05AB1E, ~~36~~ 31 bytes

```
‘€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‘#vyœN>UvyX:

```

Try it online!

---

View it ran with debug: TIO With Debug

```
‘€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‘# | Push ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE']
vyœ                   | For each list of permutations of that word...
   N>U                | Push index + 1 into register X.
      vyX:            | Replace each permutation with X.

```
> 1 votes

# Answer
# Python 3, ~~238~~ 236 bytes

```
def f(s):
 e=''
 while len(s):
  for i in range(9):
   for r in[''.join(p)for p in permutations('ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE'.split()[i])]:
    if s[:len(r)]==r:e+=str(i+1);s=s[len(r):]
 return e
from itertools import*

```

Try it online!

---

Brute-force solution, doesn't take advantage non-decreasingness of digits.

---

Thanks to @Mr. Xcoder for saving 2 bytes!
> 0 votes

# Answer
# PHP, 141 bytes

```
for($a=count_chars($argn);$c=ord($s[++$p]?:$s=[OWU,W,HG,U,FU,X,SX,G,N17.$p=0][$i-print str_repeat($i++,$x)]);)$x=$a[$i+48]+=($p?-1:1)*$a[$c];

```

older version, **151 bytes**:

```
for($a=count_chars($argn,1);$s=[OWU,W,HG,U,FU,X,SX,G,N17][+$i++];print str_repeat($i,$a[$i+48]))for($p=0;$c=ord($s[$p]);)$a[$i+48]+=($p++?-1:1)*$a[$c];

```

loops through the digits from 1 to 9, counting unique characters in the word and subtracting non-unique characters´ counts, printing the digit on the go.
Although it is printing on the go, the digit counts must be stored for the `9` case to work.

Run as pipe with `-nR` or try it online.

It would save 4 more bytes to store the digit counts in `$a[$i]` instead of `$a[$i+48]` and use ASCII `1` and `7` (in quotes) instead of the digit characters themselves.

**breakdown**

```
for(
    $a=count_chars($argn,1);                # count character occurences in input
    $s=[OWU,W,HG,U,FU,X,SX,G,N17][+$i++];   # loop through digit names
    print str_repeat($i,$a[$i+48])              # print digit repeatedly
)
    for($p=0;$c=ord($s[$p]);)                   # loop through name
        $a[$i+48]+=                                 # add to digit count
        ($p++?-1:1)*                                # (add first, subtract other)
        $a[$c];                                     # character occurences

```

`ONE` is not the only word with an `O`, so it needs to subtract the counts for `W` (only appearing in `TWO`) and `U` (only appearing in `FOUR`) and so on.
`NINE` is special, because there is no way to just subtract if I used the letters (that would require `I-X-G-F+U` or `N-O-S+W+U+X`), so I use the digit counts instead.

# PHP, 160 bytes

```
$a=count_chars($argn);foreach([W2O,U4FOR,X6SI,G8I,F5I,O1,R3,S7,I9]as$s)for(${$s[$p=1]}+=$n=$a[ord($s)];$c=ord($s[++$p]);)$a[$c]-=$n;while($$i--?print$i:$i++<9);

```

assumes all upper case input; characters may be scrambled all over.
Run as pipe with `-nR` or try it online.

**explanation**

loops through the digit words, counting their unique characters´ occurences in the input and in the process reducing the count of other characters. "Other characters" *could* mean all other characters in the word; but only considering those that will be needed later saved 19 bytes.

Transforming the `str_repeat` loop to a combined loop saved 5 bytes.

And using variable variables for the digit count saved another 8.

**breakdown**

```
$a=count_chars($argn);                              # count character occurences in input
foreach([W2O,U4FOR,X6SI,G8I,F5I,O1,R3,S7,I9]as$s)   # loop through digit names
    for(${$s[$p=1]}+=                                   # 2. add to digits count
        $n=$a[ord($s)];                                 # 1. get count of unique character
        $c=ord($s[++$p]);)                              # 3. loop through other characters
        $a[$c]-=$n;                                         # reduce character count
while(
    $$i--?print$i                                       # print digit repeatedly
    :$i++<9);                                       # loop through digits

```
> 0 votes

---
Tags: code-golf, permutations, algorithm
---


title: Tips for golfing in Fishing

text:
# Question
Title: Tips for golfing in Fishing
I recently found out about the Fishing language, and it is now a favorite of mine. However, I'm finding it difficult to do anything cool with it, including code golf. Are there any tips for golfing with Fishing to use the least characters? And any string manipulation tricks would be cool, as I am finding that difficult in Fishing.

# Answer
# `a` and `m` work on strings too

Though it isn't explicitly stated in the spec, `a` (add) and `m` (multiply), at least in the official Ruby interpreter, also work on strings.

Say you had two cells with strings in them at the end of the tape, and wanted to concatenate and print them. You could do it with `c`:

```
c{{P

```

However, as long as you don't want to preserve the original value of your first cell, you could append the second string directly onto the first with `a` and avoid having to go to the end of the tape:

```
aP

```

Now let's say you want to print 20 spaces. The naive way to do it would be to simply hardcode them:

```
`                    `P

```

As long as the cell to the right is free, though, you can save 11 instructions by using `m`:

```
` `{`20`n}mP

```

Note, however, that due to the way Ruby works, you *cannot* do this with the order of the cells reversed (i.e. multiply a number by a string); that causes an error.
> 1 votes

# Answer
# `?` doesn't need both an adjacent `=` *and* an adjacent `!`

This isn't explicitly stated in the spec either, but with the official interpreter, you do not need to surround a conditional (`?`) with both `=` *and* `!`; if one is not present and the condition matches it, the program will keep going in its original direction. An example:

```
v+CCCCCC?=CCCCCCCC
  I{`0`}! E`Zero`N
        [CCCCCCCCCCCC
         E`Not zero`N

```

This program prints takes a string and prints "Zero" or "Not zero", depending on whether it equals `"0"`. You could shave off two bytes, however, by removing the `=` sign:

```
v+CCCCCC?CCCCCCCC
  I{`0`}!E`Zero`N
        [CCCCCCCCCCCC
         E`Not zero`N

```
> 1 votes

---
Tags: code-golf, tips
---


title: Which tetromino is this?

text:
# Question
Title: Which tetromino is this?
Given an unsigned 16-bit integer ***N***, your task is to determine whether its binary representation mapped inside a 4x4 matrix is matching a tetromino shape, and if so, which shape it is.

## Matrix

Each bit of ***N*** is mapped inside a 4x4 matrix, from left to right and from top to bottom, starting with the most significant one.

**Example**:

```
N = 17600
binary representation: 0100010011000000
matrix: [ [ 0, 1, 0, 0 ],
          [ 0, 1, 0, 0 ],
          [ 1, 1, 0, 0 ],
          [ 0, 0, 0, 0 ] ]

```

## Tetromino shapes

**Base shapes**

There are 7 tetromino shapes, identified by the letters *O*, *I*, *S*, *Z*, *L*, *J* and *T*:

**Rotations and translations**

If a shape is translated and/or rotated within the 4x4 matrix, it is still considered a valid variation of the same tetromino. For instance, 17600, 1136, 2272 and 1604 should all be identified as *J* tetrominoes:

**Don't wrap!**

However, the shapes can't wrap around or be shifted beyond any boundary of the matrix. For instance, *neither* 568 *nor* 688 should be identified as *J* tetrominoes (let alone any other shape):

## Clarifications and rules

* You may take input as an integer, or directly as 16 binary digits in any reasonable format, such as a 2D array, a flat array or a delimited string.
* The input is guaranteed to be an unsigned 16-bit integer (or its equivalent representation as an array or a string).
* When a valid shape is identified, you must print or return the *letter* identifying the shape, in either lower or upper case.
* If no shape is identified, you must print or return a value that doesn't match any tetromino letter. You may also choose to return nothing at all.
* To be considered valid, the matrix must contain the exact tetromino shape without any additional cells (see 1911 and 34953 in the test cases).
* This is , so the shortest answer in bytes wins!

## Test cases

You can follow this link to get the test cases as 2D arrays.

```
0      -> false
50     -> false
51     -> 'O'
1911   -> false
15     -> 'I'
34952  -> 'I'
34953  -> false
1122   -> 'S'
3168   -> 'Z'
785    -> 'L'
1136   -> 'J'
568    -> false
688    -> false
35968  -> 'T'
19520  -> 'T'

```

# Answer
# Jelly,  ~~54 43 42~~  41 bytes

-1 byte thanks to Erik the Outgolfer (move transpose inside repeated chain)

```
T€FṀ⁸ṙ€Zµ⁺F
ZU$3Ð¡Ç€ḄṂ“çc3Ð6'G‘i’ị“¥Çıƭ⁵»

```

A monadic link taking a 2D array of integers (`1`s and `0`s) and returning a lowercase letter `oiszljt` for the respective tetromino or `w` if invalid.

**Try it Online!** or see the test suite.

Also see this program which lists all 1820 possible 2D binary arrays with exactly four bits set along with their outputs, sorted by those outputs.

### How?

This first takes all four rotations of the input. Then it shifts the set bits of each as far to the right and then as far to the bottom as possible and converts the results to binary numbers. It then looks up the minimum result in a list of the minimal such representations of each valid tetromino and uses the decremented result to index into the two concatenated dictionary words `zoist`+`jowl`, yielding `w` when no match was found.

```
T€FṀ⁸ṙ€Zµ⁺F - Link 1, shift set bits right & then down : list of lists of bits
        µ⁺  - perform the following twice, 1st with x=input, then with x=result of that):
T€          -   truthy indexes of €ach
  F         -   flatten into a single list
   Ṁ        -   maximum (the index of the right-most bit)
    ⁸       -   chain's left argument, x
     ṙ€     -   rotate €ach left by that amount
       Z    -   transpose the result
          F - flatten (avoids an € in the main link moving this into here)

ZU$3Ð¡Ç€ḄṂ“çc3Ð6'G‘i’ị“¥Çıƭ⁵» - Main link: list of lists of bits (the integers 0 or 1)
   3Ð¡                        - repeat this 3 times collecting the 4 results:
  $                           -   last two links as a monad:
Z                             -     transpose
 U                            -     upend (reverse each) -- net effect rotate 90° CW
      Ç€                      - call the last link as a monad for €ach
        Ḅ                     - convert from binary (vectorises)
         Ṃ                    - minimum (of the four results)
          “çc3Ð6'G‘           - code-page indexes = [23,99,51,15,54,39,71]
                              -   ...the minimal such results for l,z,o,i,s,t,j shapes
                   i          - 1-based index of minimum in there or 0 if not found
                    ’         - decrement
                      “¥Çıƭ⁵» - compressed words: "zoist"+"jowl" = "zoistjowl"
                     ị        - index into (1 indexed & modular, so -1 yields 'w',
                              -             0 yields 'l', 1 yields 'z', ...)

```

---

**Previous method** (54 bytes)

```
Fœr0Ḅ“çc3Ðñ'G‘i
;Z$Ḅ©f“¦µ½¿Æ‘ȯ®¬S>2ȧZU$3Ð¡Ç€Ṁ’ị“¥Çıƭ⁵»

```

A monadic link taking a 2D array of integers (`1`s and `0`s) and returning a lowercase letter `oiszljt` for the respective tetromino or `w` if invalid.

**Try it online!**

This checks there are at least three empty lines (rows+columns) and that certain patterns of bits are not present in any line (specifically the numbers 5,9,10,11, and 13), these together assure the next step wont yield false-positives. It then flattens and then floor-shifts the binary number (by striping trailing zeros before conversion) of each of the four rotations, and looks up the minimal result in a list of numbers, using the decremented result to index into the two concatenated dictionary words `zoist`+`jowl`, yielding `w` when no match was found.
> 6 votes

# Answer
# Python 3, 124 bytes

```
def f(n):
 while n&4369<n/n:n>>=1
 while n&15<1:n>>=4
 return'TJLZSIO'["rēȣc63ıGtĲȱᄑ@'̢̑@@@@Ȳq".index(chr(n))%7]

```

Try it online!

Expects an integer **n** representing a 4 × 4 binary matrix. Throws if no tetromino is found.

Line 2 slides the shape to the right until a 1 is in the rightmost column. (4369 is `0001 0001 0001 0001` in binary.) Line 3 lowers the shape until a 1 is in the bottom row. Together this turns e.g.:

```
    0 1 0 0        0 0 0 0
    1 1 1 0  into  0 0 0 0
    0 0 0 0        0 0 1 0
    0 0 0 0        0 1 1 1

```

Then we look for the index of `n` in this list:

```
 [114  275  547   99   54   15   51
  305   71  116  306  561 4369   64
   39  802  785   64   64   64   64
  562  113   23]
#   T    J    L    Z    S    I    O

```

Each column of indices equivalent modulo 7 corresponds to a tetromino shape. 64 (`@`) is used as a padding value as `n` cannot be 64 at this point in the code.

**NB.** An exception is thrown for input `0` by computing `n/n` instead of `1`.
> 28 votes

# Answer
# APL (Dyalog), ~~95~~ ~~94~~ ~~93~~ ~~89~~ 87 bytes

-2 thanks to Zacharý

Requires `⎕IO←0` which is default on many systems. Takes Boolean matrix (of any shape!) as argument. Returns nothing if the given number of bits is not four, and a blank line if the four given bits do not form a tetromino.

```
{4=+/,⍵:'OIZSJLT'/⍨∨/1∊¨(((2 2)4⍴¨1),(0 1⌽¨⊂K⌽2⊖J),(⍳3)⊖¨⊂J←1,⍪K←3↑1)∘.⍷⍵∘{⌽∘⍉⍣⍵⊢⍺}¨⍳4}

```

Try it online!

Works by creating all four rotations of the input, then looking for each tetromino in each rotation.

`{``}` anonymous function where the argument is represented by :

`,⍵` ravel (flatten) the argument

`+/` sum it

`4=` is four equal to that?

`:` if so, then (else return nothing):

`⍳4` first four **ɩ**ndices; `[0,1,2,3]`

`⍵∘{` apply the following function on each, using the input as fixed left argument

the left argument i.e. the input

`⊢⍺` yield that (separates  from )

`⌽∘⍉⍣⍵` mirror and transpose (i.e. rotate 90°)  times

`(``)∘.⍷` outer "product", but using Find\*, of the following list and the rotations:

`3↑1` take three elements from one, padding with zeros; `[1,0,0]`

`K←` store that as `K`

table (make into column vector); `[[1],[0],[0]]`

`1,` prepend a one; `[[1,1],[1,0],[1,0]]` ("J")

`J←` store as `J`

`(``)⊖¨⊂` rotate the entire J vertically, each of the following number of steps:

`⍳3` first three **ɩ**ntegers; `[0,1,2]`

we have `[[[1,1],[1,0],[1,0]],[[1,0],[1,0],[1,1]],[[1,0],[1,1],[1,0]]]` ("J", "L, "T")

`(``),` prepend the following list:

`2⊖J` rotate `J` two steps vertically; `[[1,0],[1,1],[1,0]]` ("T")

`K⌽` rotate the rows of that by 1, 0, and 0 steps respectively; `[[0,1],[1,1],[1,0]]` ("Z")

`0 1⌽¨⊂` rotate the entire array vertically, no times and once; `[[[0,1],[1,1],[1,0]],[[1,0],[1,1],[0,1]]]` ("Z", "S")

`(``),` prepend the following list:

`(2 2)4⍴¨1` reshape a one into each of a 2×2 matrix and a 4-element list; `[[[1,1],[1,1]],[1,1,1,1]]` ("O", "I")

`1∊¨` for each, is one a member?

`∨/` horizontal OR reduction (i.e. across rotations; one Boolean for each shape)

`'OIZSLJT'/⍨` use that to filter the string

* Find returns a Boolean array of same shape as its right argument, with ones indicating the top left corner of all subarrays identical to the left argument.
> 8 votes

# Answer
## JavaScript (ES6), ~~242~~ ~~212~~ ~~172~~ 164 bytes

```
x=>[...'OISZLJT'].filter((z,y)=>x.match(`^0*(${'99,33825|15,51|2145,195|561,2115|57,1059|135,71|1073'.split`,`[y].replace(/\d+/g,C=x=>x?x%2+C(x>>1)+x%2:'|')})0*$`))

```

Was supposed to be just to get the ball rolling, but I'm a little late for that ¯\\\_(ツ)\_/¯

Takes a string of bits, with rows separated by `0`s (`'0001000110001000000'` representing `0001 0011 0010 0000`) and returns an array containing the character representing the tetromino, or an array containing nothing.

This works by checking each rotation of tetromino to see if the input at any point contains the tetromino, surrounded entirely by zeroes on either side. Each tetromino is represented by one or more binary numbers:

```
0 0 0 0   -> 0000 0110 1100 0000
0 1 1 0   -> 0000001100110000000
1 1 0 0   -> 110011
0 0 0 0   -> 51

0 1 0 0   -> 0100 0110 0010 0000
0 1 1 0   -> 0100001100001000000
0 0 1 0   -> 100001100001
0 0 0 0   -> 2145

```

So to check if the input contains an S tetromino, we simply check whether it contains the binary representation of either `51` or `2145`, with only `0`s on either side.

A few of the tetrominoes have 4 orientations. If you look at the binary representations of these, each has 2 representations which are simply the mirror of the other two. To save space, the binary representation is built up forward and backward simultaneously with the recursive `C` function, allowing us to only put two of the orientations in and have the other two implied.

---

Alternate approach with charcodes:

```
x=>[...'OISZLJT'].filter((z,y)=>x.match(`^0*(${[...'÷,êÿ,óî,ûÝ,ëúüÏ,çöïþ,ßýíÞ'.split`,`[y]].map(c=>(C=n=>n?'1e'+(n%4+2)%5-0+C(n>>2):'')(c.charCodeAt())).join`|`})0*$`))

```
> 7 votes

# Answer
# Jelly, 53 bytes

```
ZL0ẋW⁸tZµ⁺ZU$3Ð¡“©©“œ“Ç¿“¦©¦“Æ½‘;Uḃ2$’¤iÐ€Ṁị“÷¶Ė¡µỵỤ»

```

Try it online!

Full program. Takes a 4x4. Prints `m` if not a tetromino, otherwise prints lowercase.
> 3 votes

# Answer
# MATL, 60 bytes

```
Itt6tIl7tl7H15vHe"4:"G@X!HYa]4$v@BIthYaEqY+4=aa]v'OSZLJTI'w)

```

Input is a binary 4×4 array (matrix), using `;` as row separator. Ouput is a letter or empty for no tetromino.

Try it online! Or verify all test cases (output has a dot appended to allow identifying an empty result).

### Explanation

The code builds 4 rotations of the input 4×4 array in steps of 90 degrees. Each rotated array is padded with 2 zeros up and down, which transforms it into a 8×4 array. The 4 arrays are vertically concatenated into a 32×4 array. The four rotated arrays within this concatenated array are "isolated" thanks to the zero-padding.

Each of the 7 possible patterns is tested to see if it is present in the 32×4 array. A loop is used for this. Each pattern is defined by two numbers, which expressed in binary give the appropriate 0/1 mask. For example, numbers `3`, `6` define the "S" shape.

The 7 sets of 2 numbers are arranged into a 2×7 matrix, from which the loop will pick each column sequentially. The matrix is defined by pushing all numbers to the stack, contatenating them into a vector, and reshaping into a 2-row matrix. Since the "I" shape is defined by number 15 followed by 0, putting it at the end allows the 0 to be implicitly filled by the reshaping function.

The mask is then padded with 3 zeros in the four directions. This is necessary so as to detect unwanted values in the input.

To see if the mask is present in the 32×4 array, the latter is transformed to bipolar form (i.e. −1/1 instead of 0/1) and convolved with the mask. Since the mask has 4 ones, matching occurs if some entry in the convolution result equals 4.

At the end of the loop, 7 false/true results have been obtained, at most one of which is true. This is used to index into a string containing the possible output letters.
> 3 votes

# Answer
# Retina, 125 bytes

```
s`(.*1){5}.*

{s`.*1111.*
I
s`.*111(.{2,4})1.*
$.1
T`234`\LTJ
s`.*11(.{2,4})11.*
$.1
T`2-90`S\OZ4-9
s`.*4.*

O#$`.
$.%`
O#$^`

```

Try it online! Link includes test cases plus a header to convert from integers to a 4×4 matrix. Explanation:

```
s`(.*1){5}.*

```

Delete the input if it contains 5 `1`s.

```
{s`.*1111.*
I

```

Check all rotations of the input (see below). If the input contains four consecutive `1`s, it's an `I`.

```
s`.*111(.{2,4})1.*
$.1
T`234`\LTJ

```

If it contains three consecutive `1`s plus a `1` on the next line underneath one of the three, then map the number of intermediate characters to the appropriate result letter.

```
s`.*11(.{2,4})11.*
$.1

```

Similarly for two adjacent `1`s adjacent to two adjacent `1`s on the next line.

```
T`2-90`S\OZ4-9

```

But also keep count of the number of rotations using the otherwise unused `0`s.

```
s`.*4.*

```

And give up if too many rotations have been performed.

```
O#$`.
$.%`
O#$^`

```

Transpose and reverse the array, thus rotating it.
> 3 votes

# Answer
# APL (Dyalog), 66 bytes

`{'TIOJSLZ-'[(¯51 144 64,,∘+⍨12J96 ¯48J64)⍳×/(+/-4×⊢)⍵/,0j1⊥¨⍳4 4]}`

Try it online!

The arg is a boolean vector.

Computes signed distances of the dots to their centre of gravity as complex numbers (real and imaginary part are ∆x,∆y) and multiplies the complex numbers together. This turns out to be a good enough invariant to distinguish among the tetrominoes.
> 2 votes

# Answer
# Perl 5, 197 + 1 (-p) = 198 bytes

```
s/(0000)*$//;1while s/(...)0(...)0(...)0(...)0/0${1}0${2}0${3}0${4}/;$_={51,O,15,I,4369,I,54,S,561,S,99,Z,306,Z,547,L,23,L,785,L,116,L,275,J,113,J,802,J,71,J,114,T,562,T,39,T,609,T}->{oct("0b".$_)}

```

Try it online!

Takes a 16 bit string as input. Outputs nothing if input is not a single tetromino.

**How?**

The two substitutions "move" the input shape to the bottom right corner. The resulting bit string is converted to an integer, then checked for in a hash of valid integers.
> 1 votes

---
Tags: code-golf, tetris, binary-matrix
---


# Question
Title: A program that outputs itself in reverse order
Well the title says it all.

* Standard loopholes apply
* Nothing to read from stdin, and output goes to stdout
* 1-byte-long programs are... nonsense. They don't qualify
* A program with a single byte repeated is also a nonsense (like `aaa`)
* **Please mark it out if your program is a palindrome**

Sample:

> A program with source code
>
> ```
> abcde
>
> ```
>
> should output
>
> ```
> edcba
>
> ```

Because this is a , the shortest program wins!

# Answer
# RProgN 2, 3 bytes

```
1
0

```

Try it online!

Pretty sure this has been submitted before, but here's one in RProgN 2.

It outputs

```
0
1

```
> 0 votes

---
Tags: code-golf
---


title: Find the shortest unique sublist

text:
# Question
Title: Find the shortest unique sublist
Given a list of lists find the shortest list that is a contiguous sublist of exactly one list.

For example if we had

```
[[1,2,3],
 [1,2,3,4],
 [2,4,5,6],
 [1,2,4,5,6]]

```

the shortest contiguous sublist would be `[3,4]` since it only appears in the second list.

If there is no unique contiguous sublist (this requires at least one duplicate entry), output an empty list. Here is an example

```
[[1,2,3],
 [1,2,3],
 [1,2]]

```

If there are multiple contiguous sublists of minimal size, you may output any one of them or a list containing all of them. For example if the input was

```
[[1,2,3],[2],[1],[3]]

```

You could output either `[1,2]`, `[2,3]` or `[[1,2],[2,3]]`. If you choose to do the latter option you may output singleton lists for the cases where there is only one solution.

The output may occur in the *same* list more than once as long as it appears in no other list. For example

```
[[1,2,1,2],[2,1]]

```

should output `[1,2]` because `[1,2]` is a sublist of the first list but not the second, even though it is a sublist of the first list in two different ways.

You may take as input a list of lists containing any type so long as that type has more than 100 possible values, i.e. no Booleans.

This is so answers will be scored in bytes with less bytes being better.

## Test Cases

```
[[1,1]] : [1]
[[1],[1]] : []
[[1,1],[1]] : [1,1]

```

# Answer
# Husk, ~~12~~ ~~14~~ 15 bytes

+3 bytes for case `[[1,1]]`

```
Ṡḟȯ¬€Ṡ-uÖLṁȯtuQ

```

Try it online!

### Explaination

```
          ṁ      -- map and concatenate
           ȯt    --   all but the first
             u   --   unique elements of
              Q  --   contiguous sublist
        ÖL       -- sort by length
Ṡḟ               -- find the first element satisfying this predicate
  ȯ¬€            --   not an element of
     Ṡ-          --   the list of sublists minus
       u         --   its unique elements

```

Note: `Ṡ f g x = f (g x) x` and this is hard to explain using the method above.
> 5 votes

# Answer
# Pyth, 15 bytes

```
halDs-M.p.:R)QY

```

Test suite

First, we generate all substrings of each input list with `.:R)Q`. Then, we generate all possible orderings, of those substring groups `.p`.

Now for the tricky part: `-M`. This folds the `-` function over each ordering list. It starts with the first substring list, then filters out all occupants of all of the other lists.

Then, the results are concatenated, ordered by length, a `[]` is appended, and then the first element of the resulting list is extracted with `h`.

This would be 4 bytes shorter if I could error on no unique sublists rather than output an empty list.
> 4 votes

# Answer
# Pyth - 20 bytes

```
Ksm.:d)QhalDfq1/KTKY

```

Test Suite.
> 3 votes

# Answer
# Java 8, 251 + 19 = 270 bytes

A very gross lambda from, minimally, `List<List>` to `List` (best to cast it to `Function<List<List<Integer>>, List<Integer>>` though). It's a brute force solution that iterates chunk lengths from 1 to the size of the largest list, in each case iterating over every chunk of that length in every list and checking each such chunk against each chunk of equal size in every other list.

Fear me, garbage collector.

```
import java.util.*;

```

```
i->{int x,l=x=0,s,t;for(List z:i)x=Math.max(x,z.size());List r=i;while(l++<=x)for(List a:i)c:for(s=0;s<=a.size()-l;s++){for(List b:i)for(t=0;t<=b.size()-l;)if(b.subList(t,l+t++).equals(r=a.subList(s,s+l))&a!=b)continue c;return r;}return new Stack();}

```

## Ungolfed lambda

```
i -> {
    int
        x,
        l = x = 0,
        s, t
    ;
    for (List z : i)
        x = Math.max(x, z.size());
    List r = i;
    while (l++ <= x)
        for (List a : i)
            c: for (s = 0; s <= a.size() - l; s++) {
                for (List b : i)
                    for (t = 0; t <= b.size() - l; )
                        if (b.subList(t, l + t++).equals(r = a.subList(s, s + l)) & a != b)
                            continue c;
                return r;
            }
    return new Stack();
}

```

Try It Online

# Java 8, 289 + 45 = 334 bytes

This is a more functional approach using streams. If there were a method on `Stream` to reduce to only elements that appear once, this solution would have beaten the one above. Assign to the same type as above.

```
import java.util.*;import java.util.stream.*;

```

```
l->{List<List>o=l.stream().flatMap(a->IntStream.range(1,a.size()+1).boxed().flatMap(n->IntStream.range(0,a.size()-n+1).mapToObj(k->a.subList(k,k+n)))).collect(Collectors.toList());o.sort((a,b)->a.size()-b.size());for(List a:o)if(o.indexOf(a)==o.lastIndexOf(a))return a;return new Stack();}

```

## Ungolfed lambda

```
l -> {
    List<List> o = l.stream()
        .flatMap(a -> IntStream.range(1, a.size() + 1)
            .boxed()
            .flatMap(n -> IntStream.range(0, a.size() - n + 1)
                .mapToObj(k -> a.subList(k, k + n))
            )
        )
        .collect(Collectors.toList())
    ;
    o.sort((a, b) -> a.size() - b.size());
    for (List a : o)
        if (o.indexOf(a) == o.lastIndexOf(a))
            return a;
    return new Stack();
}

```

Try It Online
> 2 votes

# Answer
# Haskell, ~~149~~ ~~128~~ ~~126~~ 113 bytes

```
import Data.List
f l=[x|x<-l,sum[1|y<-l,y==x]<2]
h[]=[]
h(x:y)=x
i=h.f.sortOn length.(>>=tail.nub.(>>=tails).inits)

```

Try it online!

*Saved 21 bytes thanks to Wheat Wizard, H.PWiz and Bruce Forte.*

*Saved two more bytes thanks to H.PWiz.*

*Saved 13 bytes thanks to nimi.*

**EDIT** This was the original explanation:

> * `a` is a shortcut for joining lists.
> * `s` computes all the continous sublists (all `tails` from all `inits`). Note that `nub` keeps only the first occurence of each element, so `tail` will remove the empty list from the sublists.
> * `g` merges all sublists from all given lists in a big list of sublists, and sort them by length.
> * `f` f is a filter on elements that appear only once in the big list
> * `h` is a secure version of `head`
> * `i` is the glue
>
> Quite inelegant! There should be a better solution...
> 2 votes

# Answer
# Jelly, 15 bytes

```
Ẇ€Q€ẎɓċỊµÐf⁸LÐṂ

```

Try it online!

-3 bytes thanks to Jonathan Allan
> 1 votes

# Answer
# 05AB1E, 15 bytes

```
εŒÙ}€`{γʒg}€`éн

```

Try it online!
> 0 votes

# Answer
# Pyth, 14 bytes

```
sfq1lT.gksm{.:

```

Try it here.
> 0 votes

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


title: 91 Bottles of ASCII-beer on the Wall

text:
# Question
Title: 91 Bottles of ASCII-beer on the Wall
Given a single integer `x` where `0 <= x <= 91` output a stack of bottles of beer with that many bottles (and shelves) missing. For simplicity sake I'll only show the first 6 bottles and what it would be for each of the first inputs.

Here's the stack of bottles, each number is the bottle you should remove for that input (1-indexed):

https://pastebin.com/wSpZRMV6

---

*Note, we're using 91 instead of 99 because 99 would result in an unstable stack of bottles.*

---

# Example

With 0 bottles missing (`x=0`):

```
             |=|
             | |
             | |
            /   \
           .     .
           |-----|
           |     |
           |-----|
           |_____|
        =============
         |=|     |=|
         | |     | |
         | |     | |
        /   \   /   \
       .     . .     .
       |-----| |-----|
       |     | |     |
       |-----| |-----|
       |_____| |_____|
    =====================
     |=|     |=|     |=|
     | |     | |     | |
     | |     | |     | |
    /   \   /   \   /   \
   .     . .     . .     .
   |-----| |-----| |-----|
   |     | |     | |     |
   |-----| |-----| |-----|
   |_____| |_____| |_____|
=============================
 [THERE ARE MORE UNDER THIS]

```

*For the full output of 0, see here: https://pastebin.com/ZuXkuH6s*

---

With `1` bottle missing (`x=1`):

```
         |=|     |=|
         | |     | |
         | |     | |
        /   \   /   \
       .     . .     .
       |-----| |-----|
       |     | |     |
       |-----| |-----|
       |_____| |_____|
    =====================
     |=|     |=|     |=|
     | |     | |     | |
     | |     | |     | |
    /   \   /   \   /   \
   .     . .     . .     .
   |-----| |-----| |-----|
   |     | |     | |     |
   |-----| |-----| |-----|
   |_____| |_____| |_____|
=============================
 [THERE ARE MORE UNDER THIS]

```

*Once again, this is the first two rows from here: https://pastebin.com/ZuXkuH6s (with 1 removed)...*

---

With 2 bottles missing:

```
                 |=|
                 | |
                 | |
                /   \
               .     .
               |-----|
               |     |
               |-----|
               |_____|
    =====================
     |=|     |=|     |=|
     | |     | |     | |
     | |     | |     | |
    /   \   /   \   /   \
   .     . .     . .     .
   |-----| |-----| |-----|
   |     | |     | |     |
   |-----| |-----| |-----|
   |_____| |_____| |_____|
=============================
 [THERE ARE MORE UNDER THIS]

```

---

# \[ADDITIONAL INPUTS REMOVED\]

---

With 91 bottles missing (`n = 91`):

```
:(

```

You must output an unhappy face, because you're out of beer.

---

# Rules

* Bottles are to be removed left to right.
* Shelves are removed when no beer remains on the top of the shelves.
* For an input of 0, you are outputting 91 bottles stacked in a triangle.
    + The bottom row has 13 bottles, the top has 1.
* 1 space between each bottle on each shelf.
* Shelves must be input between each row of bottles.
    + Shelves may use `=`, `-` or `#` as the character.
    + Shelves must be 3 wider (on each side) than the bottles they hold.
* This is , lowest byte-count wins.

# Answer
> 15 votes
# Charcoal, ~~99~~ 91 bytes

```
Ａ⁻⁹¹ＮθＡ¹³η:(Ｗθ«Ａ⌊⟦θη⟧ζＡ⁻θζθＡ⁻η¹ηＦζ«↑⁴↖.\↑²←|=↓³←↙¹↓.Ｐ⁶↓²Ｐ⁶↓¹Ｐ______←| »¿θ«Ｍ⁹↑Ｍ³→×=⁻×⁸ζ³↑Ｍ⁴←

```

Try it online! Link is to verbose version of code. Actually the real version is only ~~83~~ 70 bytes:

```
Ｆ¹⁵Ｆι⊞υκ:(Ｆ⁻⁹¹Ｎ«Ｆ¬⊟υ«Ｍ³±⁹×=⁺⁵×⁸⊟υ↑Ｍ⁴←»↑⁴↖.\↑²←|=↓³←↙¹↓.Ｐ⁶↓²Ｐ⁶↓¹Ｐ×_⁶←|←

```

Explanation:

```
Ｆ¹⁵Ｆι⊞υκ

```

Populate an array providing information as to where the shelves go and how long they are.

```
:(

```

Print an unhappy face, although this will be immediately overwritten by the first bottle of beer (if any).

```
Ｆ⁻⁹¹Ｎ«

```

Loop through the remaining bottles of beer.

```
   Ｆ¬⊟υ«

```

Check to see whether a shelf needs to be drawn.

```
        Ｍ³±⁹×=⁺⁵×⁸⊟υ↑Ｍ⁴←»

```

Print the shelf and position ready to draw the next bottle above it.

```
   ↑⁴↖.\↑²←|=↓³←↙¹↓.Ｐ⁶↓²Ｐ⁶↓¹Ｐ×_⁶←|←

```

Draw a bottle and position ready to draw another bottle.

# Answer
> 10 votes
# Python 3, 306 299 265 253 255 252 247 244 bytes

Quick attempt, could be optimised

**Edit:** -2 bytes thanks to @MrXcoder

**Edit:** -32 bytes as trailing spaces is not needed

**Edit:** -12 bytes by combining the two functions

**Edit:** -5 bytes thanks to @musicman523

**Edit:** +7 bytes to remove the shelf after the last row

**Edit:** -3 bytes

**Edit:** -5 bytes due to a lambda function only being used once in a map

**Edit:** -3 bytes by using the string function `center`

```
def l(y,x=13,z=" "):b=min(x,91-y);A,D="  |%s|  ","|-----|";print(y<91and(l(y+x,x-1)or"".join(map(lambda t:((t+z)*b)[:-1].center(103)+"\n",(A%"=",A%z,A%z," /   \ ",".     .",D,"|     |",D,"|_____|")))+z*(49-4*x)+"="*(x*8+5)*(x<13))or(x>12)*":(")

```

Try it online!

# Answer
> 5 votes
## JavaScript (ES6), ~~251~~ 256 bytes

**Edit:** *Saved 2 bytes thanks to @dzaima.*
**Edit:** *Added 7 bytes to fix issue with parameter. `:(`*

```
c=>(f=(c,w=13)=>c>0&&f(c-w,w-1)+(c=c<w?c:w,r=(n,s=' ')=>s.repeat(n),a='\n'+r(52-w*4),'  |=|  0  | |  0  | |  0 /   \\ 0.     .0|-----|0|     |0|-----|0|_____|'.split(0).map(x=>a+r((w-c)*8+2)+r(c,' '+x)).join('')+a+r(w*8+5,'#')),(c=91-c)?f(c).slice(6):':(')

```

Here's the (mostly) ungolfed version:

```
function (consumed) {
  let remaining = 91 - consumed;

  function inner (count, width = 13) {
    if (count <= 0) return false;

    function repeat (count, string = ' ') {
      return string.repeat(count);
    }

    const pattern = [
      '  |=|  ',
      '  | |  ',
      '  | |  ',
      ' /   \\ ',
      '.     .',
      '|-----|',
      '|     |',
      '|-----|',
      '|_____|' ];

    let clamped = Math.min(count, width);
    let alignment = '\n' + repeat((13 - width) * 4);
    let empty = alignment + repeat((width - clamped) * 8 + 2);
    let shelf = alignment + repeat((width * 8) + 5, '#');
    let bottles = pattern.map(row => empty + repeat(clamped, ' ' + row));

    return inner(count - width, width - 1) + bottles.join('') + shelf;
  }

  return (remaining) ? inner(remaining).slice(6) : ':(';
}

```

### Test code

```
const golfed =

c=>(f=(c,w=13)=>c>0&&f(c-w,w-1)+(c=c<w?c:w,r=(n,s=' ')=>s.repeat(n),a='\n'+r(52-w*4),'  |=|  0  | |  0  | |  0 /   \\ 0.     .0|-----|0|     |0|-----|0|_____|'.split(0).map(x=>a+r((w-c)*8+2)+r(c,' '+x)).join('')+a+r(w*8+5,'#')),(c=91-c)?f(c).slice(6):':(')

console.log(golfed(91)); // :(
console.log(golfed(72));
//                                                          |=|     |=|     |=|     |=|     |=|     |=|
//                                                          | |     | |     | |     | |     | |     | |
//                                                          | |     | |     | |     | |     | |     | |
//                                                         /   \   /   \   /   \   /   \   /   \   /   \
//                                                        .     . .     . .     . .     . .     . .     .
//                                                        |-----| |-----| |-----| |-----| |-----| |-----|
//                                                        |     | |     | |     | |     | |     | |     |
//                                                        |-----| |-----| |-----| |-----| |-----| |-----|
//                                                        |_____| |_____| |_____| |_____| |_____| |_____|
//     #####################################################################################################
//      |=|     |=|     |=|     |=|     |=|     |=|     |=|     |=|     |=|     |=|     |=|     |=|     |=|
//      | |     | |     | |     | |     | |     | |     | |     | |     | |     | |     | |     | |     | |
//      | |     | |     | |     | |     | |     | |     | |     | |     | |     | |     | |     | |     | |
//     /   \   /   \   /   \   /   \   /   \   /   \   /   \   /   \   /   \   /   \   /   \   /   \   /   \
//    .     . .     . .     . .     . .     . .     . .     . .     . .     . .     . .     . .     . .     .
//    |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----|
//    |     | |     | |     | |     | |     | |     | |     | |     | |     | |     | |     | |     | |     |
//    |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----|
//    |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____|
// #############################################################################################################
```

# Answer
> 2 votes
# C (gcc), 360 358 bytes

```
#define P printf(
r,i,j;char*b[]={"  |=|  ","  | |  ","  | |  "," /   \\ ",".     .","|-----|","|     |","|-----|","|_____|"};w(n){P"%*c",n,' ');}main(n,a)char**a;{(n=-atoi(a[1]))<-90?P":(\n"):({while(++r<14)if((n+=r)>0){for(j=0;j<9;++j){w(4*(13-r)+1);for(i=r;i>0;)--i<n?P b[j]),w(1):w(8);P"\n");}if(r<13){w(4*(13-r)-2);for(i=0;++i<8*r+6;)P"=");P"\n");}}});}

```

Try it online!

**Explanation:**

```
#define P printf(
r,i,j;
char*b[]={
    "  |=|  ",
    "  | |  ",
    "  | |  ",
    " /   \\ ",
    ".     .",
    "|-----|",
    "|     |",
    "|-----|",
    "|_____|"};

// function to print `n` spaces:
w(n){P"%*c",n,' ');}

main(n,a)char**a;
{
    // no beer left?
    (n=-atoi(a[1]))<-90

        // sad face
        ?P":(\n")

        // else create stack
        // using GCC extension "expression statement" `({ <statement> })` here,
        // shorter than if-else or a function call
        :({
            // loop over 13 rows
            while(++r<14)

                // found non-empty row?
                if((n+=r)>0)
                {
                    // loop over text lines of beer bottles
                    for(j=0;j<9;++j)
                    {
                        w(4*(13-r)+1);

                        // for each bottle
                        for(i=r;i>0;)

                            // print either 8 spaces or line of the bottle
                            --i<n?P b[j]),w(1):w(8);P"\n");
                    }

                    // except for last row, ...
                    if(r<13)
                    {
                        // ... print shelf
                        w(4*(13-r)-2);
                        for(i=0;++i<8*r+6;)
                            P"=");
                        P"\n");
                    }
                }
        });
}

```

# Answer
> 0 votes
# Python 2, 436 bytes

<sup>*Yikes!!*</sup>

My method is too verbose, but anyway: it essentially 'draws' each row of bottles, adds in the spaces, and then 'erases' whatever necessary, printing whatever is left.

```
B=['  |=|   ','  | |   ','  | |   ',' /   \\  ','.     . ','|-----| ','|     | ','|-----| ','|_____| ']
N=lambda r:sum(n for n in range(1,r+1))
n=input()
R=0
while N(R)<n:R+=1
L=R-n+N(R-1)
e=range(1,R)+([R],[])[L!=0]
for r in range(1,14):
    if r in e:continue
    if(r-1 in e)<1:print('',' '*(1+(13-r)*4)+'='*(r*8-3))[r!=1]
    i=(0,R-L)[r==R];w=(8*i+(13-r)*4,0)[i==0];print'\n'.join([' '*w+((13-r)*4*' '+l*r)[w:]for l in B])
if n=91:print':('

```

Halvard Hummel's is much better.

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