title: Will it halt? (Robbers)

text:
# Question
Title: Will it halt? (Robbers)
*This is the robbers' thread. The cops' thread is here.*

Your challenge is to crack a cop's submission by finding an input that makes it halt. You don't have to find out why, or all inputs that make it halt if there's more than one, or the input the cop intended, just one input will do.

Once you have cracked a submission, post a link to it in a comment or edit to the cop's post. You can also flag your submission for a mod to edit it in the cop's post. Also, post the input used and a link to the cop's post in an answer in this thread. The robber that cracks the most submissions wins.

**Multiple people can post cracks to the same cop submission, as long as they are different.**

(If SE converted your duplicate answer to a comment, you may want to vote on this feature request)

---

# Looking for uncracked submissions?

```
fetch("https://api.stackexchange.com/2.2/questions/135363/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.innerText = 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
> 52 votes
# Malbolge, Doorknob

Try it online (Thanks Dennis!)

Input for Windows: `F_⌠1234567890`

Input on Linux based system using ISO-8559-1: `F_ô1234567890`

The heart of how the Malbolge program worked is that it depended on a behavior of the Malbolge interpreter which causes an infinite loop if it encounters any instruction which is not between 33 and 126. The program was constructed such that your input would allow you to modify a single instruction.

I modified the interpreter to dump the program memory state at the beginning of execution and to also produce 'normalized' source code which takes the form of a list of op codes that will be run during the execution of the program. With that information you could (slowly) determine that even though the program took 13 inputs only the 1st and 3rd inputs actually mattered.

Looking through the normalized code and memory dump (and a touch of debugger help) I devised the following:

> a = op(input 1, 29524)
>
> b = op(input 3, a)
>
> c = op(486, b)
>
> d = op(c, 37)
>
> e = d/4 + d%3 * 3^9
>
> e must be between 33 and 126

Where `op` is the so called tritwise "op" that is described in the specification. Using this information you can write a simple program which iterates over the possible inputs (0 to 255) and finds all solutions which meet the above criteria. I had found 2219 possible solutions, some of which will probably not be working solutions (you can't input the required characters). Specifically the above inputs are based on the solution:

`(Input 1 = 70, Input 3 = 244)`

# Answer
> 15 votes
# JavaScript (in Browser)

```
document.all

```

This is falsy, surprisingly

Edit: why is `document.all` falsy?

# Answer
> 12 votes
# JS (ES6), Juan Tonina

```
+0,-0

```

Took a bit of looking in `Object.is` to find. Basically, `+0 === -0` since `===` checks them as numbers, and `0` is finite, but `Object.is` sees `+0` and `-0` as different objects. Very smart cop :)

Try it online!

# Answer
> 12 votes
# Python, Siphor

```
class A:
    i = True
    def __eq__(self, a):
        self.i = not self.i
        return self.i

a = A()
f(a)

```

We just redefine equality to behave exactly as required to get the program to terminate.

# Answer
> 8 votes
# Braingolf

```
-1

```

Any number less than `0` works.

Try it Online!

# Answer
> 8 votes
# PHP, Sisyphus

`(-0[0)> deal with it=1`

The parse\_str function changes the spaces and other characters to underscores. If you put a \[ used for Array delimiter without closing, it changes it to an underscore but has the effect of not translating the following spaces (I don't know why).

Try it online!

# Answer
> 6 votes
# JavaScript (Node.js), Adnan

`[]` and `[]` seem to work. I tried a bunch of them including `null`, `undefined`, `NaN`...

`[] >= [] && [] <= [] && [] != []` evaluates to true.

Moral of the story: JavaScript is *weird*.

Try it online!

# Answer
> 6 votes
# JavaScript (ES7), Arnauld

## Standard

`"8e7"` is solution

```
var crack_me = (x=0)=>{for(;~x/x.length**3!=-2962963;);}

var key = "8e7"

crack_me(key)
console.log("stopped :)")
```

## Hack

No need to calculate this number, we can redefine `length` property

This sets `~x/x.length**3!=-2962963` to `false`

```
var crack_me = (x=0)=>{for(;~x/x.length**3!=-2962963;);}

var key = {toString:()=>"2962962",length:"1"}

crack_me(key)
console.log("stopped :)")
```

## Operators priority

`~` bitwise not is first

`** exponentiation` second

`/ division` third

# Answer
> 5 votes
# Bash, Veedrac

```
LD_TRACE_LOADED_OBJECTS

```

Try it online!

From the `ld.so(8)` manpage:

> **LD\_TRACE\_LOADED\_OBJECTS**
>
> If set (to any value), causes the program to list its dynamic dependencies, as if run by `ldd(1)`, instead of running normally.

# Answer
> 5 votes
## Mathematica, JungHwan Min

```
Unevaluated@Throw@"hammertime"

```

No clue whether this is the intended solution, but it passes in an expression that doesn't get evaluated until it's referenced as `#` inside the function, which will cause it turn return from the function immediately without doing any further evaluation. You can see that the function is actually called (instead of just throwing the exception before even invoking the function) by changing the function to:

```
#0[Print@"stop";#;$IterationLimit=∞]&

```

Which will indeed print the `stop` before throwing the error.

# Answer
> 5 votes
# R, Jarko Dubbeldam

```
function(x)if(is.list(x))return(1)

```

First time contributing anything, so do call out any mistakes I've made in format.

Pretty sure this is valid. Just a rewrapping of is.list(), right?

# Answer
> 4 votes
# Retina, PunPun1000

```
11111

```

Try it online!

Any input with *n* `1`s where the sum of the divisors of *n+1* is equal to *n+1* should work.

# Answer
> 4 votes
# Node.js, Adnan

`{}` and `{}` or any 2 objects are the two inputs. I don't even understand how this works.

Here's JS's amazing object compare logics:

```
console.log({} == {});
console.log({} === {});
console.log({} > {});
console.log({} < {});
console.log(!!{});

console.log({} >= {});
console.log({} <= {});
```

# Answer
> 4 votes
# Ruby

```
exit

```

without newline. `3.send('exit')` surely isn't equal to `5`, but it executes `Kernel#exit`:

> Initiates the termination of the Ruby script by raising the SystemExit exception

It's possible to call `exit` on `3` because:

> The Kernel module is included by class Object, so its methods are available in every Ruby object \[as private methods\].

`abort` also works:

> Terminate execution immediately, effectively by calling Kernel.exit(false). If msg is given, it is written to STDERR prior to terminating.

# Answer
> 4 votes
# JavaScript (Node.js), programmer5000

Already cracked, but mine is slightly different :) Don't have enough rep to comment over in the cops. Also feel free to edit to fix formatting, my first post here.

Mainly I set `__proto__` equal to a function that throws. Taken from looking at the Mozilla page for proto. (Sorry, low rep, can't post a link.)

```
x = {}
let No = function () { throw 'halted' }
x.__proto__ = new No()

```

```
f = x=>{while(x.__proto__);}

```

Try it online!

EDIT: Got some rep, so here's the link: Mozilla `__proto__`

# Answer
> 4 votes
# Bash, Sisyphus

```
kill 0

```

Fortunately, `kill` is a shell builtin.

Try it online!

# Answer
> 4 votes
# Javascript, programmer5000

## Max string length

Uses a string with a length one less than what your engine supports. When adding `"h"` to this string, an error is thrown. Try it online!

```
function getAlmostMaxLenStr() {
  var prevBases = [];
  var base = "a";
  try {
    while(true) {
      prevBases.push(base);
      base += base;
    }
  } catch(e) {}
  for (var i = prevBases.length-1; i>=0; --i) {
    try {
      base += prevBases[i];
    } catch (e) {}
  }
  return base;
}
f(getAlmostMaxLenStr());

```

## Cross-origin block

Heavily inspired by the answer from @jadkik94, but works everywhere. Creates a cross-origin iframe, then passes the `.contentWindow` of said iframe. This fails when the function tries to use the value due to cross-origin safety.

```
let f=x=>{
  try {
    console.log(x+"h"); // we don't want to lock up your browser, do we ;)
  } catch (e) { console.log("Halted!\n",e); }
}
let iframe=document.createElement("iframe");
const url = location.host.indexOf("google") === -1 ? "https://google.com" : "https://stackexchange.com";
iframe.src=url;
iframe.onload=a=>f(iframe.contentWindow);
document.body.appendChild(iframe);
```

## Primitive value

Variant of the `.toString()` answers - this just uses `toPrimitive` instead. It returns an object as the primitive value, which Javascript doesn't know how to handle (so it throws an error). Try it online!

```
f({
  [Symbol.toPrimitive](){return {}}
});

```

# Answer
> 3 votes
# Octave, Stewie Griffin

Input: `exit`

Reasoning: `input` evalutes whatever is input. `exit` exits the program.

Try it online!

# Answer
> 3 votes
## Javascript (NOT node.js), programmer5000

This can't be added because it creates an object that has no toString because a new `Set` does not inherent prototypes from from `Object`.

input:

```
new Set()

```

Try it online!

# Answer
> 3 votes
# JavaScript (Babel Node), Conor O'Brien

(Repost, accidentally put in cops.) Not sure what was intended but positive decimals that aren't enormous all seem to work.

Also I guess I still can't comment in Cops.

```
f(0.1)
console.log('done')

```

Try it online!

# Answer
> 3 votes
# Python 2, Foon

```
__import__("os")._exit(0)

```

What it says on the tin, basically.

Try it online.

# Answer
> 3 votes
# Bash 4.2, Dennis

```
PATH=1

```

Clearly not the intended solution, because it works on newer bash as well.

Try it online.

# Answer
> 3 votes
## Python 3 (CPython), Veedrac

```
a=('',(type,),{})
X=type(*a)(*a)
X.__class__=X

```

Try it online!

# Answer
> 3 votes
# Python 3, Siphor

This was fun. We need to make the `type(x) != str` check pass, so we need to control the return value of `type()`. We have to override the `__class__` attribute and replace it with a custom object, that extends `type`, which has the `__ne__` method replaced by one that always returns false. This makes it pass the type check, but the search will fail because `o` is not a str.

```
class m(type):
    def __ne__(a,b):
        return False
class c:pass
o=c()
o.__class__=m("",(c,),{})
f(o)

```

# Answer
> 3 votes
# C#, TheLethalCoder

```
System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

```

Or any other nullable class.

# Answer
> 3 votes
# R, Jarko Dubbeldam

Just an invalid regex.

```
"["

```

Try it online.

# Answer
> 3 votes
# Python, Siphor

```
f('t=False')

```

Crashes due to an `UnboundLocalError`. I think this is hapening because my `t=False` overrides the higher-scoped `t` with the local `t`, but it's not set at the time of the loop, causing the crash.

TIO

# Answer
> 3 votes
# Commodore 64 Basic, Mark

If I understood this correctly (and it's entirely plausible I have not), you just need to overflow the floating point variable.

```
9999999999999999999999999999999999999999999999999999999999999999.9

```

# Answer
> 3 votes
# Bash 4.2, Dennis

```
-9223372036854775808/-1

```

Why though, Dennis? y u do dis?

# Answer
> 3 votes
# C#, TheLethalCoder

```
new char[0]

```

`string.Empty` (`""`) is always interned. Therefore, an empty array or `null` will work.

# Answer
> 3 votes
# Husk, Leo

Pass 4 arguments! It only works with 0-3. You can't do it with less because the arguments aren't actually used.

Try it online.

# Answer
> 3 votes
# JavaScript, programmer5000

```
window[0]

```

Works on the Code Golf StackExchange page on Firefox (i.e. `while(window[0] + "h");` throws a `Error: Permission denied to access property Symbol.toPrimitive` error in the console and exits)

# Answer
> 3 votes
# BASIC, Stilez

```
https://www.youtube.com/watch?v=9NcPvmk4vfo

```

This input halts the program. Weird choice, but it works.

# Answer
> 3 votes
# brainfuck, Jerry

```
B0000

```

Try it online!

Edit: This is the list of all 5-character input that makes the program halts, in range `[a..z]`: (Warning: large text file)

And this is all input in `WordData[]` of Mathematica 10:

```
{"aesop", "agape", "annon", "cloak", "daunt", "fagus", "filch", \
"gomel", "hijab", "jakes", "jerry", "rebut", "rover", "ruddy", \
"sewed", "trine", "villa"}

```

Perhaps `jerry` is the expected input.

Explanation:

First, we can see that there are 5 `,` signs in the program, therefore 5 characters are required. Call their character code `{i0, i1, i2, i3, i4}` respectively.

And, to "decrypt" the code:

```
>>,>,>,>,>,                     m0 = i0; m1 = i1; m2 = i2; m3 = i3; m4 = i4;
[-----------<-<+<--<--->>>>]    m3 -= m4 / 11; m2 += m4 / 11; m1 -= 2*m4 / 11; m0 -= 3*m4 / 11; m4 = 0;
<++<<+<++                       m3 += 2; m1 ++; m0 += 2;
[----->+<]                      m1 += m0 / 5; m0 = 0;
>
[----------------->+++++++<]    m2 += 7*m1 / 17; m1 = 0;
>
[----->>+<<]                    m4 += m2 / 5; m2 = 0;
>>
[-<->]                          m3 -= m4; m4 = 0;
<
[--->++++++<]                   m4 += 6*m3 / 3; m3 = 0;
>
[--->+<]                        m5 += m4 / 3; m4 = 0;
+>-                             m4 ++; m5 --;
[-----------------<+>]          m4 += m5 / 17; m5 = 0;
<
[-->-<]                         m5 -= m4 / 2; m4 = 0;
>+                              ++m5;
[+-]                            while (m5 != 0);

```

Where initially the tape has the form

```
... m-2 m-1 m0 m1 m2 m3 m4 m5 ...
     ^ (data pointer at initial position = m-2)

```

So, input

```
m5 = 0;
m0 = i0; m1 = i1; m2 = i2; m3 = i3; m4 = i4;
m3 -= m4/11; m2 += m4/11; m1 -= 2*m4/11; m0 -= 3*m4/11; m4 = 0;
m3 += 2; m1++; m0 += 2;
m1 += m0/5; m0 = 0;
m2 += 7*m1/17; m1 = 0;
m4 += m2/5; m2 = 0;
m3 -= m4; m4 = 0;
m4 += 6*m3/3; m3 = 0;
m5 += m4/3; m4 = 0;
m4++; m5--;
m4 += m5/17; m5 = 0;
m5 -= m4/2; m4 = 0;
++m5;

```

(note: over modulo 256, all divisions will halt, except the `m5 -= m4/2` is because of at that point m4 is even)

into Mathematica gives

```
m5 = (117414 + 77 i0 + 385 i1 + 935 i2 - 4675 i3 + 419 i4)/238425

```

`m5 == 0` can be transformed to (mod 256)

```
i4 := Mod[222 + 177 i0 + 117 i1 + 211 i2 + 225 i3, 256]

```

Loop `i0, i1, i2, i3` through all combination of `a..z` gives 46413 results, of which 17 of them are English words.

# Answer
> 3 votes
# Swift 3, Alexander

```
extension Bool {
    prefix static func !(val: Bool) -> Bool {
        return false
    }
}

```

Add above the loop.

# Answer
> 2 votes
# JS (Node.js)

```
NaN

```

In JS, `NaN !== NaN`

# Answer
> 2 votes
# JavaScript (ES6), programmer5000

```
"\0"

```

Try it online!

The condition was `!x||x>="\n"`. Any single char in an ASCII table with a code less than `\n` will work.

# Answer
> 2 votes
# JS (ES6)

```
"   "

```

Any character with a code less than 10 should work; I've used a `tab` character above, which SE converts to spaces.

# Answer
> 2 votes
# Retina

A newline followed by a `1` works. I found it right away.

```

1
```

**Try it online**

# Answer
> 2 votes
# MATL, Luis Mendo (not the intended solution)

The empty input stops the program and thorws the following error:

> input: reading user-input failed!

Try it online!

# Answer
> 2 votes
# cQuents, Step Hen

Anything followed by a space and a positive integer. The space separates inputs, and the extra input becomes the number of the term to output.

Try it online!

# Answer
> 2 votes
# MATL, Luis Mendo

```
0/0

```

MATL evaluates 0/0 as NaN. Since NaN != NaN it does not loop

Try it online!

# Answer
> 2 votes
# Octave, Stewie Griffin

Any undefined input such as `a` will work: Try it online!

Defined values would not work, because `|` in a `while` environment is short-circuiting, so when it sees `1`, it will already become `true`, no matter what the value of `x` is. So, the only way to make it halt is to make `x=input('')` halt, i.e. by giving it undefined inputs.

# Answer
> 2 votes
## Javascript (NOT node.js)

Feel like this is cheating based on the last answer...

```
{toString:_=>{throw''}}

```

# Answer
> 2 votes
# C (gcc), dj0wns

```
%s%s

```

Try It Online!

The offending command essentially evaluates to this and throws a seg fault when it tries to read a second string from beyond d, since there is no 5th argument to the function.

```
char b[256];
char*d = "abcd";
snprintf(b,4,"%s%s",d)

```

# Answer
> 2 votes
# C (gcc), Justin

With input `%s`, the program crashes.

```
#include<stdio.h>
int main(){char c[9];while(1){scanf("%8s",c);printf(c);}}

```

Try it online!

# Answer
> 2 votes
# RProgN 2, ATaco

Cracked, with input `#`. I have no idea why, I think `C` evals, and `#` is a comment.

```
` .iS‘"{".C

```

Try it online!

# Answer
> 2 votes
# Javascript, Conor O'Brien

```
NaN

```

Yes, `typeof NaN` returns `"number"`.

# Answer
> 2 votes
# C (gcc), dj0wns

The intended solution is probably:

```
%n

```

This treats `char *a` as a writable `unsigned int`, but since it is assigned to a constant string, this invokes undefined behaviour which on TIO gives me:

> /srv/wrappers/c-gcc: line 5: 18569 Segmentation fault (core dumped) ./.bin.tio "$@" \< .input.tio

# Answer
> 2 votes
# Node.js, Евгений Новиков

input:

```
{__proto__:null}

```

Try it online!

The input gets applied to an object. My input is an object with the same name as the native functions (`__proto__`) which will get applied to the object in the while condition and will override the native functions (such as `toString` and `valueOf`), causing an error when the program tries to cast the object to true/false for the while loop (because the necessary functions are missing and broken).

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

The answer is `'0'`.

```
f=x=>{try{for(;!x||x!=0||x instanceof Object;);}catch(e){for(;;);}}

f('0')

```

Try it online!

# Answer
> 2 votes
# Javascript (Node.js), programmer5000

```
Object.prototype

```

Object.prototype is the root prototype for all other objects, but it can't obviously have a prototype itself, because that would create a loop. Edit: I think this also works:

```
Object.create(null)

```

# Answer
> 2 votes
# JavaScript (Node.js), Haumed Rahmani

JavaScript uses floats for everything, so...

```
f(100000000000000000)

```

Try it online!

# Answer
> 2 votes
# Java 8, Socratic Phoenix

```
-32760

```

Try it online.

The hardest part was recognising that taking \>1s didn't mean it was stuck in a loop :P.

This is just due to the constant cache; the equality check is actually for identity.

# Answer
> 2 votes
# JavaScript, Step Hen

```
" "

```

Try it online!

# Answer
> 2 votes
# Python 3, Veedrac

```
>>> import sys
>>> class A(type): pass
...
>>> for _ in range(sys.getrecursionlimit()+1):
...   class A(type, metaclass=A): pass
...
>>> T(A)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in T
  File "<stdin>", line 2, in T
  File "<stdin>", line 2, in T
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object

```

# Answer
> 2 votes
# JavaScript, w0lf

This is the same hack as many others, really. There's probably a smarter solution, but this works.

```
{toString:1}

```

This just throws an error when calling `toString`.

# JavaScript, w0lf v2

Same deal, no exception.

```
function(){ let x=0; return {toString: () => x++} }()

```

I'm pretty sure that's not the normal way to make anonymous objects with locals, but I figure someone will correct me in the comments.

# Answer
> 2 votes
# Python 3, Veedrac

One value for which the program stops (with a `ZeroDivisionError`) is:

```
324835776096020208287573140963456

```

Try it online!

***Edit:** I'm not completely sure this is the smallest such value, but I will continue to check.*

***Edit2:** OK, I've been looking for smaller solutions and haven't been able to find any. I cannot demonstrate that this is the smallest such value, but I'm pretty confident that it is.*

---

### Explanation

The algorithm does the following (considering the binary representations of the numbers):

* `p`, `n`, and `c` are initialized to `0` (no bits set)
* at each step, it consumes the 12 rightmost bits from `x` (the input)
* out of these 12 bits, the 3 leftmost are discarded (`&511`) and only the remaining 9 bits are used. The value represented by these 9 bits is assigned to `b`.
* out of the 9 bits, at most one must be set (`b` must be 0, or a power of 2), otherwise `b&(b-1)` will make the inner `while` loop forever.
* the bit that is currently set in `b` will be set in `p`, `n`, and `c`
* `p` is shifted 1 bit to the right (`p>>=1`)
* `n` is shifted 1 bit to the left (`n*=2`)
* in the next iteration, the bit set in `b` must be set in neither `p`, `n`, nor `c` (otherwise the `(p|c|n)&b` condition will make the inner `while` loop forever)

The objective is at the end to have all 9 bits in `c` set (it will be equal to 511 and therefore the last line will fail with the `ZeroDivisionError`), otherwise the last `while` will loop forever.

So, I was looking for a minimal way to make `x` out of 12-bit chunks, such that:

* every chunk will have one of the rightmost 9 bits set
* no chunk will "collide" diagonally with any of the former ones

The code I used to generate `x` with the smallest value I found is this:

```
chunks = [
        0b000000000001,
        0b000000000100,
        0b000000010000,
        0b000001000000,
        0b000100000000,
        0b000000000000,
        0b000000000010,
        0b000000001000,
        0b000000100000,
        0b000010000000,
]

x = 0
for c in (chunks):
    x += c
    x <<= 12
x >>= 12

print(x)

```

# Answer
> 2 votes
## JavaScript (Node.js) by Alex Varga

Updated with what I'd intended to post, thanks to Patrick Roberts' comment!

```
{valueOf:_=>process.exit(0)}

```

Try it online!

# Answer
> 2 votes
# JavaScript, programmer5000

```
Symbol.split

```

Try it online!

# Answer
> 2 votes
# Pyth, isaacg

Seems to halt every time. Input:

```
.q

```

Try it here!

# Answer
> 2 votes
# Pyth, isaacg

```
.q

```

This quits the program.

Try it online.

# Answer
> 2 votes
# C, Steadybox

```
1597463007 1065353216

```

Try it online.

This one was clever.

# Answer
> 2 votes
# Pyth, isaacg

```
exec(input())
__import__("os")._exit(1)

```

I call this "privilege escalation" :P.

# Answer
> 2 votes
# C++, ecatmur

```
struct C { int m; };
int C::* t = &C::m;

```

Try it online!

For some reasons, default initialization of pointer-to-member make that `-1`, which become `true` when cast to `bool`.

# Answer
> 2 votes
# R, Jarko Dubbeldam

`"unlist"`

Though it's just one more function that could be added to the exceptions - I doubt it's the intended solution.

---

Two more cracks: `'is.vector'` and `'return'`. These both work on the modified (`list(0)`) version.

# Answer
> 2 votes
# JavaScript, iovoid

```
this.constructor.constructor("return process")().exit()

```

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js \>= 6.0), Patrick Roberts

```
{__proto__:Function,toString:_=>process.kill(0)}

```

This probably isn't the intended answer, but it does work. It kills the process without giving either the exit handler or the exception handler a chance to run. Sending to PID 0 is shorter than to `process.pid` and sends the signal to all processes in the current process group.

# Answer
> 2 votes
# Python 2, by veedrac

```
import os, functools
class A:__int__ = os.abort
k(functools.partial(int, A()))

```

# Answer
> 2 votes
# Python 3, E.D. (Fixed)

The input `0526315789473684210344827586206896551724137931020408163265306122448979591836734693877551` halts the fixed program. Since each of the three chunks are separate from each other, you can compute them individually, then combine them together. A coworker of mine figured out the logic and wrote the script to generate this answer.

Also, the fix didn't entirely work as an input of `"0"*88+"1"` will halt the program as well, since the check for a nonzero `n` checks the whole string, while only `n[:88]` is used in the calculations. So, any input of the form `"0"*88+A` where `A` is a string where all elements are digits, and at least one is nonzero, will cause the program to halt.

Try it online!

# Answer
> 2 votes
# Javascript (Node.js), A username

Most inputs to the program will actually throw an error (`null`, `0`, `[]` etc), but the below solution halts without an error:

```
f({ replace: () => {} })

```

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), cracks A username's challenge

```
f('`W`')

```

Try it online!

There are multiple ways to make this fail with an error (try a single backtick) but this evaluates to this

```
return +[`W`]

```

This results in `NaN`, and `NaN !== NaN`.

# Answer
> 1 votes
# cQuents, Step Hen

```
1 2

```

Try it online!

Essentially, anything that matches `/^.+ \d+$/` is valid input that will halt the program.

# Answer
> 1 votes
# Java

The strings `__.-._.-._.-.-.-.-.-._.-._._.-.-._.` and `__-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-` work, with a minor bug: Integer.toHexString doesn't give a leading `0x`, under Java 8. (I didn't try other versions.) Trimming it from the source makes it work fine.

# Answer
> 1 votes
# Java, tuskiomi

Fatally errors when the two arguments '\_-\_-\_-\_-\_-' and '\__________' are given.

# Answer
> 1 votes
# JavaScript (ES6), programmer5000

```
null

```

The condition was `typeof x!=="object"||x`; apparently `null` is an object but falsey in JavaScript.

Try it online!

# Answer
> 1 votes
# JavaScript, programmer5000

```
null

```

That's basically it.

# Answer
> 1 votes
# JavaScript, programmer5000

```
new Buffer(268435440)

```

Throws an error when it is coerced into a string.

Try it online!

Got it from this request for better error documentation.

# Answer
> 1 votes
# JS, Step Hen

```
991

```

Lots of obfuscation!

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js)

```
g("13")(13/321)

```

It works, apparently you can replace 13 with 33, 53, etc

# Answer
> 1 votes
# Python 2, Foon

Crack or hack? I'm not sure which this is yet...

Windows:

```
exit()
<ctrl>C

```

Where `<ctrl>` is the actual key modifier. This will eval `exit()` in the first pass of the loop and catch the keyboard interrupt in the second. `quit` will work in place of `exit` too.

(Nix replace `<ctrl>C` with `<ctrl>D` ?)

# Answer
> 1 votes
# Python 3.5, Siphor

```
"\r def t():pass"

```

Calling `f("\r def t():pass")` will redefine the "inner" `t` to a function that does nothing prior to it being created inside the "outer" `t`.

# Answer
> 1 votes
# Python 2, Quelklef

```
def x():
    import ctypes
    ctypes.cast(1, ctypes.POINTER(ctypes.c_int))[0]

f(x)

```

I'm sure this isn't the intended solution, but a segfault counts, right?

# Answer
> 1 votes
# Python 2, Quelklef

```
def f(x):
	try:x()
	except:1
	while True:1
def x():global True;True=False
f(x)

```

Try it online!

Redefines `True` to `False`.

# Answer
> 1 votes
# J, miles

Input: `''` (the empty vector). Errors with an `index error`.

```
$:@#~^:(0([=[e.{#])#~) ''

```

This approach (erroring out) will work for infinity, floats, and non-positive numbers.

The intended approach is probably an imaginary number, such as `2j2`, which returns a result.

```
   $:@#~^:(0([=[e.{#])#~) 2j2
2j2

```

Let's decompose the program:

```
$:@#~^:(0([=[e.{#])#~)
$:@                       call this function (recurse)
   #~                     with the input repeated itself times
     ^:(             )    if:
        0(    f   )#~         f(0, #~ y)
          [=[e.{#]

dyad:
[ = [ e. { # ]  x = 0, y = #~ y
           #    repeat
             ]     y
         {         y[0] times
    [ e.        check if 0 is in this list
[ =             check if that is false

```

So, we want an input **y** such that `(0{y) # (#~ y)` contains a zero. When using an imaginary number as `y = a + bi`, we get:

```
#~ y
y # y
(a + j. b) # y
(a # y) , (b # 0)

```

Which gives us `b` zeroes in the input. This will make the aforementioned condition false, and this only run once.

# Answer
> 1 votes
# JavaScript by Grant Davis

```
({t:1,get x(){ return this.t--; }})

```

`getter` is powerful. you may also try `Proxy`.

# Answer
> 1 votes
# Bash, Dennis

```
//

```

Try it online.

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

code:

```
x=>{try{for(;!x||x!=0||x instanceof Object||typeof x!='object';);}catch(e){for(;;);}}

```

input:

```
{valueOf:g=>{Object=Number;return 0}}

```

Try it online!

`!x`: x resolves to true !true resolves to false

`x!=0`: `valueOf` is overridden and returns 0. `0!=0` is false Also sets Object to Number for next step

`x instanceof Object`: `Object` now points to `Number` and x is an Object not a Number so this resolves to false

`typeof x!="object"`: x is an object so `typeof x` returns "object". `"object"!="object"` is false

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

```
1.00000001

```

Any value near 1 under the rounding threshold will make it.

Try it online!

# Answer
> 1 votes
# R, Rift

```
expression(T <- 0)

```

Sets `T` to a false value. I don't know R, seems to work.

Try it online.

# Answer
> 1 votes
# JS, 11bytes / 18bytes

code:

```
 f=a=>{while(!Array.isArray(a)||!a.length);a.map(_=>{for(;;);})}

```

cracked (throws no error):

```
f(Array(5))

```

cracked (throws error):

```
 a=[1];a.map=1;f(a)

```

# Answer
> 1 votes
# JavaScript, Step Hen

One input that stops the program is the object literal `{valueOf: () => false}`:

```
var f=x=>{while(!(x&&x==false));};
f({valueOf: () => false});
console.log('Done!');
```

# Answer
> 1 votes
# JavaScript, Step Hen

```
[]

```

Try it online!

# Answer
> 1 votes
## Python 3 (CPython), Veedrac

```
import gc
gc.set_debug(gc.DEBUG_SAVEALL)
gc.collect()
l(gc.garbage[0])

```

Try it online!

# Answer
> 1 votes
# JS, Step Hen

```
"void 0"

```

Simple: the 5th char is , the string doesn't have any trailing or leading whitespace, and evaled results in `undefined`.

# Answer
> 1 votes
# R Jarko Dubbeldam

> `f=function(x)while(1)if(length(x))grep(x,'')`

Fails with a function argument, e.g.,

```
f(mean)
# Error in as.character(pattern) :
  cannot coerce type 'closure' to vector of type 'character'

```

Try it online!

# Answer
> 1 votes
# anyfix, Mayube

```
-5

```

Easy enough once you learn the neat language. Basically once you make 0 from the addition, the rest is fluff.

Try it online.

# Answer
> 1 votes
# JavaScript by w0lf

```
Object(NaN)

```

Another crack, more elegant way.

# Answer
> 1 votes
# Python 3, Magenta

```
def f(x):
 y=str(x)
 while not(x and(y[-1]+y[:-1])==str(2*x)):a=1

```

The trick is to find a number `x` which when multiplied by two is equal to itself when all the digits are shifted to the right, with wrapping.

Isaacg found the first number for which this works (`105263157894736842`), and using the same pattern, I found a bunch more inputs: `210526315789473684`, `421052631578947368`, `315789473684210526` all work.

Because I didn't make the original crack, and @Isaacg hasnt posted this yet, I made this as CW.

Note that these numbers are formed from the decimal expansion of 1/19.

# Answer
> 1 votes
# R, Jarko Dubbeldam

```
expression(quit())

```

Try it online.

# Answer
> 1 votes
# CPython 3.6, by wizzwizz4

```
lambda *a,main=__import__("__main__"):(exec("""main.bool=lambda:True"""),1/0)

```

# Answer
> 1 votes
# C++, SIGSEGV

```
0

```

Segfaults.

Try it online!

# Answer
> 1 votes
# C++, ecatmur

Truly the most beautiful code I have ever written.

```
#include <iostream>

auto killmenow = 0;

struct Tee {
    Tee() { if (killmenow++ > 10) { exit(0); } }
};

auto t = Tee{};

int main() {
    f<Tee &, t>(t);
}

```

This question really confuses me, ergo the above disaster.

Try it online.

# Answer
> 1 votes
Python, Sudo Bash

```
import signal

class x:
    @property
    def x(self):
        signal.alarm(1)
    def __str__(self):
        return 'x.x'

```

# Answer
> 1 votes
# Python 3 by Veedrac

A single **0xff** byte for UTF-8, or anything else that cannot be decoded by the selected encoding.

Try it online!

# Answer
> 1 votes
# Python 3.5, Siphor

```
'yield'

```

TIO

# Answer
> 1 votes
# Swift, Alexander

```
func ==(lhs: Int, rhs: Int) -> Bool {
    return false
}

```

Redefine the `==` operator to always return `false`. This means that now, `0` works because `0 == 0` is now false, and `0 != 0` is still false

Alternatively, redefine the `!=` operator to always return `false` so that every integer *other* than `0` will halt.

# Answer
> 1 votes
# Python 3: totallyhuman's post, 143 bytes

```
def f(o):
 while bool(o)==bool(o):0

# My code starts here

class A:
	def __init__(s):s.a=False
	def __bool__(s):s.a=not s.a;return s.a

f(A())

```

Try it online!

# Answer
> 1 votes
# Python 2, Alex Hall

```
__builtin__,True,

```

Try it online!

We override `True` to the empty string, which is falsy.

# Answer
> 1 votes
# Python 3, Alex Hall

```
eval(input())
__import__("os")._exit(0)

```

Try it online!

Clearly not the intended answer. Bypasses the length limit by evaluating the input.

# Answer
> 1 votes
# Batch, SteveFest

Just undo the quote.

```
"&&exit

```

(with a trailing )

Another unintended solution:

```
"|exit

```

# Answer
> 1 votes
# C (gcc), dj0wns

```
%s12345678

```

Try it Online!

Since c is only defined as an 8 (`'\b'`) character array and the fgets is passed a second argument of 12 (`'\f'`) longer strings begin to corrupt d which is located after c on the stack. Adding enough characters will cause the snprintf to segfault when it tries to reference the pointer d which has been corrupted

# Answer
> 1 votes
# Python, Alex Hall

```
"%307d"%1

```

This creates a truthy string consisting of 306 spaces followed by `1`.

# Answer
> 1 votes
# Python, by veedrac

```
import sys;sys.settrace(-1)

```

The `-1` can be replaced with any other non-callable object

# Answer
> 1 votes
# Python 3, Alex Hall

```
1<<1017

```

Try it online!

# Answer
> 1 votes
# 05AB1E, MilkyWay90

```
1

```

TIO

Pretty easy one, all I had to do was look up the command list for the language.

# Answer
> 1 votes
# Python 3, Makonede

```
class A:
    def __eq__(self, x):
        exit()

f(A())

```

Try it online!

The solution checks if `x == x`, and then loops while `a or not a`. This is always truthy. You cannot override the logical NOT operator so there is no way for this to be falsy. However, you can just input a custom object that exits the program when it is checked with `==` so the function is still called and runs but exits before it can hit the infinite loops.

# Answer
> 1 votes
# Javascript, cracks Ethertyte's answer

```
f(eval('delete Object.prototype.hasOwnProperty'))

```

Try it online!

I can't believe I didn't think of this earlier.

# Answer
> 1 votes
# Python 3, cracks hakr14's challenge

```
class x():
 def __init__(s):
  global isinstance
  isinstance=lambda x,y:0

f(x())

```

Try it online!

Simply replaces `isinstance` with a lambda returning `0`, causing the `isinstance` call to always return 0, instantly exiting the loop.

# Answer
> 0 votes
# JavaScript (ES6), programmer5000

```
"Infinity"

```

The condition first tests if the input has a `.slice` method (aka if it's a string or an array) and gets the absolute value of the numeric representation of the string/array. This is then added to `0` and checked against `Infinity`.

Try it online!

# Answer
> 0 votes
# Add++, caird coinheringaahing

The empty input. The answer is pretty pointless, since it never runs in an infinite loop.

Try it online!

# Answer
> 0 votes
# Braingolf, Mayube

### Answer

```
163

```

### Code explanation:

```
1+[#£-0!e>:$_1>|]

1+                  # Add 1 to the input
  [             ]   # While bottom of the stack > 0..
   #£               #   Push 163
     -              #   Subtract from the input
      0             #   Push 0
       !            #   Peek top of the stack
        e           #   If greater than zero, do..
         >          #     Rotate the stack one to the right
          :         #   Else..
           $_       #     Discard top of the stack
             1      #     Push
              >     #     Rotate the stack one to the right
               |    #   End ifelse

```

Which results in outputting `0`.

Try it online!

# Answer
> 0 votes
# Node.JS, programmer5000

```
x = {}
x.constructor = false
f(x)

```

We define an object where `x.constructor` is false so it terminates immediately

TIO

# Answer
> 0 votes
# Python 3, Erik Brody Dreyer

While error raising cracks are 10 a penny, a simple non-erroring one is just 88 zeros in a row:

```
def fun(n):
while not (int(n[17]+n[:17])==2*int(n[:18]) and int(n[45]+n[18:45])==3*int(n[18:46]) and int(n[87]+n[46:87])==5*int(n[46:88])):
    print("Ha")
fun("0"*88)
print("halted and did not error")

```

**Try it online!**

# Answer
> 0 votes
# JavaScript (Node.js), programmer5000

```
Object.defineProperty(a={},"__proto__",{value:false,writable:false})

```

Try it online!

Simple enough. A truthy object who's `__proto__` is defined to be false permanently.

# Answer
> 0 votes
# JavaScript (Babel Node), programmer5000

`new Set()` was posted as a crack but didn't work for me (Try it online!), so I made one that doesn't throw, but does create a TypeError.

```
let f=x=>{while(x+"h");}

```

```
class Halt {
    toString() {
	return {}
    }
}
f(new Halt())

```

Try it online!

P.S. The solution I really wanted was to negate the charCode somehow and be errorless but I couldn't get that to not resolve to concatenation. :)

EDIT: An more modern alternative:

```
f( {
    [Symbol.toPrimitive] (hint) {
        return {}
    }
} )

```

# Answer
> 0 votes
# JavaScript (browser), tsh

```
document.all

```

I started trying falsy values. `document.all` did the job.

# Answer
> 0 votes
# JavaScript (Node.js), Step Hen

`Array(4)` works because it is creating an empty array of size 4 and the string representation of that is `,,,`.

Try it online!

# Answer
> 0 votes
# Java 8, Socratic Phoenix

These anonymous class answers are getting a bit overdone, but it works and I have no shame.

```
import java.util.ArrayList;

// ...

new ArrayList<Object>() {
    public boolean isEmpty() {
        boolean ret = !super.isEmpty();
        add(new Object());
        return ret;
    }
}

```

You can avoid the import if you're patient enough to build out all the `List` methods. I'm not.

Try it online.

# Answer
> 0 votes
# JavaScript (Node.js) by Alex Varga

```
({toString(){return this.t--;},t:1})

```

Try it online!

# Answer
> 0 votes
# R, Gregor

```
expression(set.seed(5))

```

Similar principle to my other R answer. Seems to work.

Try it online.

# Answer
> 0 votes
# R, Jarko Dubbeldam

just break out of the while loop

```
expression(break)

```

# Answer
> 0 votes
# R, Jarko Dubbeldam

it's my first time that I participated at something like this... hope i got it right.

```
.Internal(.invokeRestart(list(NULL, NULL), NULL))

```

Try it online!

# Answer
> 0 votes
# CPython 3.6, by wizzwizz4

```
1/0

```

Almost certainly not the intended solution, but it works

# Answer
> 0 votes
# SmallTalk, Yimin Rong

```
1086

```

I should have trusted him.

# Answer
> 0 votes
# JavaScript, Birjolaxew

```
Object.freeze({[Symbol.toPrimitive]() { raise; }})

```

# Answer
> 0 votes
# JavaScript (ES7), iovoid

```
46474849

```

WolframAlpha made the calcs trivial.

# Answer
> 0 votes
# JavaScript (ES7), Step Hen

I've found 5 solutions that work, so far:

```
[]

new Array()

Array.prototype

String.prototype

Number.prototype

```

Strangely, `Object.prototype` doesn't work.

# Answer
> 0 votes
# JavaScript, Birjolaxew

```
new Proxy({},{get(){throw''}})

```

# Answer
> 0 votes
# Befunge 93, Dopapp

```
<

```

The code calculates `(ord(input) - 3*4*5) / 0 = (ord(input) - 60) / 0`, which gives *Infinity* or *-Infinity* for any ascii value `≠60` and *NaN* for ascii value `60` (\<) on the linked interpreter. The part `#v_@` only terminates if the top value of the stack is falsy, which is only the case for *NaN*.

# Answer
> 0 votes
# Python3, by AlexHall

Probably not what OP had in mind:

```
help.__doc__

```

Here's a test on my system:

```
Python 3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 12:22:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
>>> s = "help.__doc__"
>>> len(s)
12
>>> eval(s)
"Define the builtin 'help'.\n\n    This is a wrapper around pydoc.help that provides a helpful message\n    when 'help' is typed at the Python interactive prompt.\n\n    Calling help() at the Python prompt starts an interactive help session.\n    Calling help(thing) prints help for the python object 'thing'.\n    "
>>> len(eval(s))
307

```

It doesn't work with Python2 on my system.

# Answer
> 0 votes
# BrainF, MilkyWay90

`0`

I brute forced this one. My first guess was correct. And two subsequent inputs to make sure I was right.

Oops?

# Answer
> 0 votes
# JavaScript (Node.js)

I've done some research, and find out that JavaScript that only uses `()[]+!` is called JSFuck. With the help of JScrewIt and JS Minify, I've found the solution:

```
"[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[!![]+!![]+!![]]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]])()(([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(!![]+[])[(![]+[])[!![]+!![]+!![]]+([][[]]+[])[+[]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]]()[+!![]+[+[]]]+![]+(!![]+[])[(![]+[])[!![]+!![]+!![]]+([][[]]+[])[+[]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]]()[+!![]+[+[]]])()[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](([]+[])[(![]+[])[!![]+!![]+!![]]+([][[]]+[])[+[]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]]()))[+!![]+[+[]]]+([][[]]+[])[+[]]+(!![]+!![]+[])+(!![]+!![]+!![]+!![]+!![]+!![]+[])+(+[]+[])+(!![]+!![]+!![]+!![]+!![]+!![]+[])+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]])+(([]+[]+[]+[]+[]+[]+[]+[]+[]+[]))"

```

Try it online!

## Explanation

```
[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[!![]+!![]+!![]]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]])()( // eval function, copied from https://jscrew.it/ with only Node.js support
                                                                                // '"'
    ([]+[])[                                                                                // ''['fontcolor']() == '<font color="undefined"></font>'
        (![]+[])[+[]]+                                                                                // f
        (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+              // o
        ([][[]]+[])[+!![]]+                                                                                // n
        (!![]+[])[+[]]+                                                                                // t
        ([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+             // c
        (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+              // o
        (![]+[])[!![]+!![]]+                                                                                // l
        (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+              // o
        (!![]+[])[+!![]]                                                                                // r
    ]()[                                                                                // ''['fontcolor']()['12'] == 'u'
        +!![]+                                                                                // 1
        [!![]+!![]]                                                                                // 2
    ]+
    (                                                                                // '\\'
        +[![]]+                                                                                // NaN
        [][                                                                                // []['fill']
            (![]+[])[+[]]+                                                                                // f
            ([![]]+[][[]])[+!![]+[+[]]]+                                                                                // i
            (![]+[])[!![]+!![]]+                                                                                // l
            (![]+[])[!![]+!![]]                                                                                // l
        ][                                                                                // []['fill']['constructor']
            ([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+         // c
            (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+          // o
            ([][[]]+[])[+!![]]+                                                                                // n
            (![]+[])[!![]+!![]+!![]]+                                                                                // s
            (!![]+[])[+[]]+                                                                                // t
            (!![]+[])[+!![]]+                                                                                // r
            ([][[]]+[])[+[]]+                                                                                // u
            ([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+         // c
            (!![]+[])[+[]]+                                                                                // t
            (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+          // o
            (!![]+[])[+!![]]                                                                                // r
        ](                                                                                // []['fill']['constructor']('return/false/')() == /false/
            (!![]+[])[+!![]]+                                                                                // r
            (!![]+[])[!![]+!![]+!![]]+                                                                                // e
            (!![]+[])[+[]]+                                                                                // t
            ([][[]]+[])[+[]]+                                                                                // u
            (!![]+[])[+!![]]+                                                                                // r
            ([][[]]+[])[+!![]]+                                                                                // n
                                                                                // /
            (!![]+[])[                                                                                // 'true'['sub']() == '<sub>true</sub>'
                (![]+[])[!![]+!![]+!![]]+                                                                                // s
                ([][[]]+[])[+[]]+                                                                                // u
                (                                                                                // b
                    [][                                                                                // []['entries']
                        (!![]+[])[!![]+!![]+!![]]+                                                                                // e
                        ([][[]]+[])[+!![]]+                                                                                // n
                        (!![]+[])[+[]]+                                                                                // t
                        (!![]+[])[+!![]]+                                                                                // r
                        ([![]]+[][[]])[+!![]+[+[]]]+                                                                                // i
                        (!![]+[])[!![]+!![]+!![]]+                                                                                // e
                        (![]+[])[!![]+!![]+!![]]                                                                                // s
                    ]()+                                                                                // []['entries']() == Object [Array Iterator] {}
                    []                                                                                // []['entries']() + [] == '[object Array Iterator]'
                )[!![]+!![]]                                                                                // '[object Array Iterator]'[2] == 'b'
            ]()[+!![]+[+[]]]+                                                                                // '<sub>true</sub>'[10] == '/'
            ![]+                                                                                // 'false'
            (!![]+[])[                                                                                // / (see above)
                (![]+[])[!![]+!![]+!![]]+
                ([][[]]+[])[+[]]+
                (
                    [][
                        (!![]+[])[!![]+!![]+!![]]+
                        ([][[]]+[])[+!![]]+
                        (!![]+[])[+[]]+
                        (!![]+[])[+!![]]+
                        ([![]]+[][[]])[+!![]+[+[]]]+
                        (!![]+[])[!![]+!![]+!![]]+
                        (![]+[])[!![]+!![]+!![]]
                    ]()
                    +[]
                )[!![]+!![]]
            ]()[+!![]+[+[]]]
        )()[                                                                                // /false/['constructor']
            ([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+         // c
            (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+          // o
            ([][[]]+[])[+!![]]+                                                                                // n
            (![]+[])[!![]+!![]+!![]]+                                                                                // s
            (!![]+[])[+[]]+                                                                                // t
            (!![]+[])[+!![]]+                                                                                // r
            ([][[]]+[])[+[]]+                                                                                // u
            ([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+         // c
            (!![]+[])[+[]]+                                                                                // t
            (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+          // o
            (!![]+[])[+!![]]                                                                                // r
        ](                                                                                // /false/['constructor']('<sub></sub>') == /<sub><\/sub>/
            ([]+[])[
                (![]+[])[!![]+!![]+!![]]+                                                                                // s
                ([][[]]+[])[+[]]+                                                                                // u
                (                                                                                // b
                    [][
                        (!![]+[])[!![]+!![]+!![]]+
                        ([][[]]+[])[+!![]]+
                        (!![]+[])[+[]]+
                        (!![]+[])[+!![]]+
                        ([![]]+[][[]])[+!![]+[+[]]]+
                        (!![]+[])[!![]+!![]+!![]]+
                        (![]+[])[!![]+!![]+!![]]
                    ]()+[]
                )[!![]+!![]]
            ]()                                                                                // '<sub></sub>'
        )
    )[+!![]+[+[]]]+                                                                                // 'NaN/<sub><\\/sub>/'[10] == '\\'
    ([][[]]+[])[+[]]+                                                                                // u
    (!![]+!![]+[])+                                                                                // 2
    (!![]+!![]+!![]+!![]+!![]+!![]+[])+                                                                                // 6
    (+[]+[])+                                                                                // 0
    (!![]+!![]+!![]+!![]+!![]+!![]+[])+                                                                                // 6
    ([]+[])[                                                                                // '"'
        (![]+[])[+[]]+
        (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+
        ([][[]]+[])[+!![]]+
        (!![]+[])[+[]]+
        ([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+
        (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+
        (![]+[])[!![]+!![]]+
        (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+
        (!![]+[])[+!![]]
    ]()[
        +!![]+
        [!![]+!![]]
    ]
)+
(([]+[]+[]+[]+[]+[]+[]+[]+[]+[]))                                                                                // Padding to 4321 characters

```

# Answer
> 0 votes
# JavaScript (Node.js), programmer5000

```
null

```

! \> Will cause an error "TypeError: Cannot read property 'constructor' of null".

`undefined` also works.

---
Tags: code-golf, decision-problem, cops-and-robbers
---


title: Generate a Nine-Ball Pool rack

text:
# Question
Title: Generate a Nine-Ball Pool rack
# Introduction

Nine-Ball is a popular pool game played casually and as a competitive sport.

There is one of each numbered ball, with the numbers 1 to 9. The game starts with all 9 of the balls in a diamond shaped rack, like so:

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

```

The 1 ball is always at the front of the diamond, and the 9 ball is always in the middle, with all the other balls placed randomly (the "X"s in this diagram):

```
  1
 X X
X 9 X
 X X
  X

```

# Challenge

Your challenge, given no input, is to generate and output random 9-ball pool racks in the text format of the examples. Extra surrounding whitespace is allowed.

Output may be through any convenient method, standard loopholes apply. A new rack MUST be generated on each run, you cannot just produce a single randomly-chosen rack every time. Extra surrounding whitespace is allowed.

# Example Outputs

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

```

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

```

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

```

Least bytes per language wins.

# Answer
# , 61 bytes

```
cat(paste0(c("  1
 ","","
","9 ","
 ","","
  "),sample(2:8)))

```

Try it online!

Prints alternately the proper whitespace/newline (with 1 and 9 included) and elements of a random permutation of \\$\\{2,\ldots,8\\}\\$.
> 12 votes

# Answer
# Python 3, ~~91~~ 87 bytes

```
from random import*
print("  1\n %d %d\n%d 9 %d\n %d %d\n%3d"%(*sample(range(2,9),7),))

```

Try it online!

-4 bytes thanks to xnor (final `\n %d` -\> `\n%3d` and `tuple(...)` -\> `(*...,)`)
> 11 votes

# Answer
# Bash or any Bourne Shell, with modern coreutils, 54 52 bytes

```
printf '  1
 %s %s
%s 9 %s
 %s %s
  %s' `shuf -i2-8`

```

Try it online!

-2 bytes thanks to @dzaima (use shuf -i option for an implicit seq)

Originally:

```
printf '  1
 %s %s
%s 9 %s
 %s %s
  %s' `seq 2 8|shuf`

```

Try it online!

I saved one byte by not including a newline at the end of the source, and another by not including one at the end of the output.

Explanation:

`seq 2 8` outputs `2 3 4 5 6 7 8` on separate lines.

`|shuf` randomly reorders them. (This is what needs modern coreutils.)

`printf <formatstring> <args>` does a C-like printf of the arguments with the format string.
> 10 votes

# Answer
# JavaScript (ES6), 89 bytes

```
_=>`  1
 X X
X 9 X
 X X
  X`.replace(/X/g,g=_=>m^(m|=1<<(i=Math.random()*9|0))?i:g(),m=3)

```

Try it online!

### How?

We replace each "X" in the template with a random integer \\$0\le i\<9\\$ such that the \\$i\\$-th bit in the bitmask \\$m\\$ is not already set, and we simultaneously update \\$m\\$.

We start with \\$m=3\_{10}=000000011\_2\\$ so that \\$0\\$ and \\$1\\$ are never chosen.
> 6 votes

# Answer
# Charcoal, ~~27~~ 25 bytes

```
Ｆ⁷⊞υ‽⁻Ｅ⁷⁺²κυ↖⪪⁺⪫⪪⪫υω⁴9¦1³

```

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

```
Ｆ⁷

```

Loop 7 times.

```
⊞υ‽⁻Ｅ⁷⁺²κυ

```

Create a list of the integers from 2 to 8, perform set difference with the list of integers collected so far, select a random integer, and push it to the empty list. This shuffles the integers from 2 to 8.

```
⁺⪫⪪⪫υω⁴9¦1

```

Concatenate the integers, insert a `9` after the fourth, and append a `1`. Edit: Saved 2 bytes by using @JonathanAllan's trick to insert the `9`.

```
↖⪪...³

```

Split the string into a 3×3 grid and print it diagonally thus achieving the desired output.
> 6 votes

# Answer
# Python 3, 128 bytes

```
from random import*
l=[1]+sample(range(2,9),7)
l.insert(4,9)
for i in[1,2,3,2,1]:print(f"{' '.join(map(str,l[:i])):^5}");l=l[i:]

```

Try it online!

Unfortunately not even close to the straightforward solution, but I spent so much time on this that I still wanted to share it.

# Ungolfed:

```
from random import *

# Generate random sampling and ensure 1st element is 1
l = [1] + sample(range(2, 9), 7)
# Ensure 5th element is 9
l.insert(4, 9)

for i in [1, 2, 3, 2, 1]: # Numbers of digits per row
    # Take i numbers from the beginning of l, join them with spaces
    # Then center the resulting string in a field of length 5 and print
    print(f"{' '.join(map(str,l[:i])):^5}")
    # Drop the just printed numbers
    l = l[i:]

```

It can be shortened but then it no longer makes use of the nifty `:^5` format specifier:

# Python 3, 112 bytes

```
from random import*
l=[1]+sample(range(2,9),7)
l.insert(4,9)
for i in[1,2,3,2,1]:print(' '*(3-i),*l[:i]);l=l[i:]

```

Try it online!

A funny one without `insert` which bounces the 9 into the middle by slicing with a step size of 2:

# Python 3, 115 bytes

```
from random import*
l=[1]+sample(range(2,9),7)+[9]
for i in[2,4,6,4,2]:print(' '*(3-i//2),*l[:i:2]);l=l[i:]+l[1::2]

```

Try it online!
> 6 votes

# Answer
# Kotlin, ~~102 95 93~~ 92 bytes

```
{List(7){it+2}.shuffled().fold("  1\n XX\nX9 X\n XX\n  X"){s,c->s.replaceFirst("X", "$c ")}}

```

Try it online!
> 5 votes

# Answer
# Ruby, ~~66~~ 52 bytes

```
$><<"  1
 %d %d
%d 9 %d
 %d %d
  %d"%[*2..8].shuffle

```

Try it online!

Also quite a boring answer, similar to the Perl and Bash solutions.

Saved 14 bytes thanks to Value Ink!
> 5 votes

# Answer
# Jelly, 24 bytes

```
7ẊŻŒHj8‘;€⁶⁽¦ỵD¤œṖz⁶ZṚ€Y

```

A full program which prints the result.

**Try it online!**

### How?

```
7ẊŻŒHj8‘;€⁶⁽¦ỵD¤œṖz⁶ZṚ€Y - Main Link: no arguments
7                        - seven
 Ẋ                       - shuffle (implicit range [1..7])
  Ż                      - prepend a zero
   ŒH                    - split in half
     j8                  - join with an eight
       ‘                 - increment (vectorises)
        ;€               - concatenate each with:
          ⁶              -   a space character
                œṖ       - partition before indices:
               ¤         -   nilad followed by link(s) as a nilad:
           ⁽¦ỵ           -     2479
              D          -     digits -> [2,4,7,9]
                  z⁶     - transpose with space filler
                    Z    - transpose
                     Ṛ€  - reverse each
                       Y - join with newline characters
                         - implicit, smashing print

```
> 4 votes

# Answer
# Perl 6, 51 bytes

```
printf '  1
 %s %s
%s 9 %s
 %s %s
  %s',pick *,2..8

```

Try it online!

I'm not really happy with how boring this solution is.
> 4 votes

# Answer
# PowerShell, 60 bytes

```
'  1
 {0} {1}
{2} 9 {3}
 {4} {5}
  {6}'-f(2..8|Sort{Random})

```

Try it online!

-17 bytes thank you @Veskah for cleaning up whitespaces

Originally:

```
'
   1
 {0}  {1}
{2}  9  {3}
 {4}  {5}
   {6}
' -f (2..8 | Sort {Get-Random})

```
> 4 votes

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

```
4>þ`ṚŒḄYṣ1µ7ẊŻs4j8‘;€⁶ż@o⁶

```

Try it online!

A full program that takes no arguments and outputs a pool rack.

## Explanation

```
4>þ`                       | Outer table using 1,2,3,4 on both sides and > as the the function [0,1,1,1],[0,0,1,1],[0,0,0,1],[0,0,0,0]
    Ṛ                      | Reverse [0,0,0,0],[0,0,0,1],[0,0,1,1],[0,1,1,1]
     ŒḄ                    | Bounce [0,0,0,0],[0,0,0,1],[0,0,1,1],[0,1,1,1],[0,0,1,1],[0,0,0,1],[0,0,0,0]
       Y                   | Join with newlines
        ṣ1                 | Split at 1s
          µ                | Start a new monadic chain
           7Ẋ              | Shuffle list of 1..7
             Ż             | Prepend with zero
              s4           | Split into pieces of length 4
                j8         | Join with 8
                  ‘        | Increment by 1
                   ;€⁶     | Append space to each
                      ż@   | Zip with list generated above
                        o⁶ | Replace 0s with spaces

```
> 3 votes

# Answer
# Perl 5, 62 bytes

```
printf"  1
 %d %d
%d 9 %d
 %d %d
  %d",sort{int(rand 3)-1}2..8

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~18~~ 16 bytes

```
Y8L.r1†9ª•26Ià•Λ

```

-2 bytes thanks to *@Grimmy* by using a fixed length of `2` with some directions duplicated.

Try it online.

**Explanation:**

```
Y            # Push 2
8L           # Push a list in the range [1,8]
  .r         # Randomly shuffle it
    1†       # Filter the 1 to the front
      9ª     # Append a trailing 9 (i.e. [1,3,4,8,5,2,6,7,9])
•26Ià•       # Push compressed integer 33557713
Λ            # And use the Canvas builtin with those three values

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•26Ià•` is `33557713`.

*Canvas explanation:*

The Canvas builtin takes three arguments:
1. The lengths of the lines to 'draw', which in this case is the fixed length of `2`.
2. The string to 'draw', which in this case is the list `[1,#,#,#,#,#,#,#,9]` (where the `#` are random digits in the range `[2,8]`).
3. The directions, which in this case is `33557713`. These will be the directions `[↘,↘,↙,↙,↖,↖,↗,↘]`.

With these arguments, it will draw as follows (let's take the random list `[1,3,4,8,5,2,6,7,9]` as example here):

```
2 characters (1,3) in direction 3 (↘):
1
 3

2-1 characters (4) in direction 3 (↘):
1
 3
  4

2-1 characters (8) in direction 5 (↙):
1
 3
  4
 8

2-1 characters (5) in direction 5 (↙):
1
 3
  4
 8
5

2-1 characters (2) in direction 7 (↖):
 1
  3
   4
2 8
 5

2-1 characters (6) in direction 7 (↖):
  1
   3
6   4
 2 8
  5

2-1 characters (7) in direction 1 (↗):
  1
 7 3
6   4
 2 8
  5

2-1 characters (9) in direction 3 (↘):
  1
 7 3
6 9 4
 2 8
  5

```

NOTE: Since we use a fixed length of `2`, the directions are leading in drawing the Canvas. So the trailing `3` in the directions `33557713` is mandatory for outputting the `9` here, whereas my previous 18-byter used the leading `3` with implicit wraparound to output the `9`, since the lengths-list were leading for drawing instead.

See this 05AB1E tip of mine for a more in-depth explanation of the Canvas builtin.
> 3 votes

# Answer
# Dyalog APL Extended, 38 bytes

```
{5 5⍴(~2⊤29010619)⍀∊⍕¨∊,∘9¨@4⊢1,1+?⍨7}

```

Try it online!
> 2 votes

# Answer
# Red, 90 bytes

```
t: random[2 3 4 5 6 7 8]foreach c{  1
 ; ;
; 9 ;
 ; ;
  ;}[prin either c >#":"[take t][c]]

```

Try it online!
> 2 votes

# Answer
## SAS, 160 Bytes

```
data;array j[9](1:9);do i=1to 1e4;l=int(2+7*ranuni(0));m=int(2+7*ranuni(0));n=j[l];j[l]=j[m];j[m]=n;end;put+2j[1]/+1j[2]j[3]/j[4]j[9]j[5]/+1j[6]j[7]/+2j[8];run;

```

Ungolfed:

```
data _null_;
  array j[9] (1:9);       **Define and populate an array;
  do i = 1 to 1e4;        **Iterate ten thousand times;
    l=int(2+7*ranuni(0)); **make a random int;
    m=int(2+7*ranuni(0)); **make another random int;
    n=j[l];               **save num in first slot;
    j[l]=j[m];            **swap second to first slot;
    j[m]=n;               **swap original first to second slot;
  end;
  put +2j[1]/+1j[2]j[3]/j[4]j[9]j[5]/+1j[6]j[7]/+2j[8];
                          **outputs the string, / is linebreak, +# is shift over, always adds one space;
run;

```

If I wanted to do it a bit "better" but longer, I would use rand("integer",2,8);, as that is a better random number distribution, but 1 char longer each line...

I'm pretty sure PROC IML would be much smaller, as that would be more similar to the R/Python implementation. Base SAS has tools to sort rows randomly, but not columns/variables. I figure doing 10,000 random swaps is sufficiently randomized here (probably as random as any of the other implementations, anyway); could easily do 1 billion random swaps for no more characters, but 10k seems enough.
> 2 votes

# Answer
# Keg, 62 bytes

```
2345678(~z%|&(~z%|')&^)  ,,1.
, ,. ,.
,. ,9. ,.
, ,. ,.
,  ,,.

```

Try it online!

Remove the `z%`' s for -4 bytes but a *really long* execution time.

This:

* Pushes the numbers 2-8 onto the stack.
* Shuffles everything in a very interesting way.
* Prints out the required shape.
> 1 votes

# Answer
# C (GCC) ~~161~~ 158 bytes

-3 bytes from ceilingcat

```
#define B,b[i++]
b[]=L"";main(a,t,i){srand(time(0));for(i=b;--i;b[a]=t)*b=b[a=rand(t=*b)%7];printf("  1\n %d %d\n%d 9 %d\n %d %d\n  %d"B B B B B B B);}

```

`L""` has non-printing characters that I can't get to show in SE is equivalent to `{2,3,4,5,6,7,8}`

this code makes the assumption that the address of `b` is at least 14 in order to guarantee all results are possible

Try it online!
> 1 votes

# Answer
# APL, 37 chars/bytes

```
2⌽t⌽↑⍕¨((t←1 2 3 2 1)/⍳5)⊆1,5⌽9,1+?⍨7

```

permutation of numbers from 2 to 8

```
1+?⍨7

```

add leading 9, shift 5 positions to the left, add leading 1

```
1,5⌽9,

```

replicate numbers from 1 to 5, 1-2-3-2-1 times respectively

```
(t←1 2 3 2 1)/⍳5

```

make 5 nested vectors of length 1-2-3-2-1 respectively

```
((t←1 2 3 2 1)/⍳5)⊆

```

transform numerical arrays into char vectors

```
⍕¨

```

nested vectors into matrix

shift each line 1-2-3-2-1 positions to the left respectively, and then 2 more for every line

```
2⌽t⌽

```
> 1 votes

# Answer
# PHP, ~~83~~ 81 bytes

*83 bytes*

```
<?=($l=range(2,8))&&shuffle($l)?vsprintf("  1\n %d%2d\n%d 9 %d\n%2d%2d\n%3d",$l):0;

```

Try it online!

---

*81 bytes*

Splitting code into 2 fragments to save 2 characters. Thanks for the comment @manatwork.

```
<?$l=range(2,8);shuffle($l)?><?=vsprintf("  1\n %d%2d\n%d 9 %d\n%2d%2d\n%3d",$l);

```

Try it online!
> 1 votes

# Answer
# Vyxal, ~~42~~ 32 bytes

```
`  1
 % %
% 9 %
 % %
  %`7ɾ1+Ṗ℅%

```

Try it Online!

-10 thanks to lyxal.
> 1 votes

# Answer
# Java 10, ~~140~~ 139 bytes

```
v->{var r="  1\n x x\nx 9 x\n x x\n  x";for(int d=9,m=3;m<511;r=r.replaceFirst("x",d+""))for(;m==(m|=1<<(d*=Math.random()));d=9);return r;}

```

Port of *@Arnauld*'s JavaScript answer, so make sure to upvote him as well!

Try it online.

**Explanation:**

```
v->{                // Method with empty unused parameter and String return-type
  var r="  1\n x x\nx 9 x\n x x\n  x";
                    //  Result-String, starting at:
                    //  "  1
                    //    x x
                    //   x 9 x
                    //    x x
                    //     x"
  for(int d=9,      //  Temp integer for the random digit, starting at 9
          m=3;      //  Bit-mask `m`, starting at 3 (binary 000000011)
          m<511     //  Loop as long as `m` is not 511 yet (binary 111111111):
          ;         //    After every iteration:
           r=r.replaceFirst("x",d+""))
                    //     Replace the first "x" with digit `d`
    for(;m==        //   Inner loop as long as `m` is unchanged after
            (m|=    //   `m` is bitwise-ORed with:
                1<< //    2 to the power
                   (d*=Math.random()));
                    //    a random digit in the range [0,9)
      d=9);         //     After every iteration: reset `d` to 9 again
  return r;}        //  And finally return the result-String

```
> 0 votes

# Answer
# C (gcc), 139 bytes

```
char a[7],c;r(){for(srand(time(0));c=rand()%7,a[c]++;);c+=2;}f(){printf("  1\n %d %d\n%d 9 %d\n %d %d\n  %d",r(),r(),r(),r(),r(),r(),r());}

```

Generates a random number 0-6, tests if that number has been generated before, and if not, prints it.

Try it online!
> 0 votes

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


title: Build a Twitter-quine

text:
# Question
Title: Build a Twitter-quine
A short while, ago, @daniel\_ernston sent the following challenge to @StackCodeGolf on Twitter:

> @StackCodeGolf Your task is to build a program that uses the API of your choice to tweet its own source code. Shortest code wins, of course.

# Answer
> 10 votes
### JavaScript, 38 characters

```
window.open("http://tinyurl.com/erjk34");

```

Here is the tweet, in all its glory: https://twitter.com/kevinaworkman/status/575425948562014209

And here is my previous entry at 95 characters:

```
function q() {
window.open("https://twitter.com/intent/tweet?text="+encodeURIComponent(q+";{q();}"));
};{q();}

```

### And if that's not cheating...

### HTML, 22 characters

http://tinyurl.com/erjk35

# Answer
> 0 votes
# Python 2, 118 bytes

```
import webbrowser,urllib
webbrowser.open("https://twitter.com/intent/tweet?text="+urllib.quote(open(__file__).read()))

```

(Can't) Try it online! (Run locally)

¯\\\_(ツ)\_/¯

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


# Question
Title: Generate a mantis's head (symmetrical triangle)
Given guaranteed strictly positive **integers \\$w\\$ and \\$n\\$**, output

* An **equilateral triangle array** with **side length \\$w\\$**, filled with two distinct, consistent values. I'll call these `0` and `1` but they do not have to be equal to `0` and `1`.
* The **number of `1`s** inside this array **must be equal to \\$n\\$**.
* The output triangle **must be symmetrical**, meaning that it is the same when flipped horizontally or diagonally (**your choice**).
* An equilateral triangle array can be an array with \\$w\\$ elements where for \\$1\\$ to \\$w\\$ (inclusive), there is a sub-array with that number of elements inside of \\$w\\$ (for example, but it may be outputted via ascii-art, see below).

(\\$n\\$ values are guaranteed to fit in the triangle)

## Examples

```
w=3, n=1
  1
 0 0
0 0 0

w=3, n=2
  0
 1 1
0 0 0

w=3, n=3
  1
 1 1
0 0 0

w=3, n=4
  0
 1 1
1 0 1

w=3, n=5
  0
 1 1
1 1 1

w=3, n=6
  1
 1 1
1 1 1

```

## Valid Output Format List

In this case the distinct values are `1` and `0`. Possible output triangles (all considered equivalent) with `1`s at their corners and center and a width of 4 are:

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

```

```
1
00
010
1001

```

```
[[1],[0,0],[0,1,0],[1,0,0,1]]

```

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

```

```
[[1],[0,0],[0,1,0],[1,0,0,1]]

```

```
1
0
00
11
00
0
1

```

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

```

---

here is a test case validator in Jq, takes `{"w": w, "n": n, "a": result you wish to check}` (in the JSON array format like `[[1],[0,0],[0,1,0],[1,0,0,1]]`)

# Answer
# Jelly, 15 bytes

```
RØ.ṗŒpFS=ɗƇUƑƇḢ

```

Try it online!

-1 byte thanks to caird coinheringaahing

```
RØ.ṗŒpFS=ɗƇUƑƇḢ  Main Link; accepts w as the left argument and n as the right argument
R                Range; [1, 2, ..., w]
 Ø.ṗ             [0, 1] ~ cartesian power ~ ^
    Œp           Cartesian Product of ^'s items - this gets all valid triangles of the right size
      ---ɗƇ      Keep elements where
       S         the sum of
      F          the triangle flattened
        =        equals (right argument)
             Ƈ   Keep elements where
            Ƒ    the element is the same when
           U     each sub-list is reversed
              Ḣ  Get the first such triangle

```
> 10 votes

# Answer
# JavaScript (ES6), 54 bytes

A much shorter approach. I think this is equivalent to @ovs' answer.

Expects `(n)(w)`. Returns a list of lists, from bottom to top.

```
n=>g=w=>w?[Array(w).fill(n<w?0:(n-=w,1)),...g(w-1)]:[]

```

Try it online!

---

# JavaScript (ES6),  ~~88~~  85 bytes

This one inserts \\$1\\$'s as soon as it can.

Expects `(n)(w)`. Returns a list of lists, from bottom to top.

```
n=>g=w=>w?[(h=q=>k--?k--?[q=n>1?--n/n--:0,...h(),q]:[n&&n/n--]:[])(k=w),...g(w-1)]:[]

```

Try it online!
> 7 votes

# Answer
# Japt, 20 bytes

```
ò1 Ô®>V?Zî0:(VµZ,Zî1

```

Try it

* we start from the biggest row, if `n` is not smaller than its length we fill the row with 1s
* we can always put the rest of 1s on the next lines.
* filling entire rows gives a specular triangle.

```
- input: U=w , V=n
ò1 Ô   - range[1..w] reversed
®      - map to Z=>
>V?    - if Z>n
Zî0     * string of Z 0s
:(     - else
VµZ,    * n-=Z and..
Zî1     * string of Z 1s

```
> 6 votes

# Answer
# Python 3.8, 47 bytes

Returns a nested list of booleans.

```
f=lambda w,n:w*[1]and[[x:=n>=w]*w]+f(w-1,n-w*x)

```

Try it online!
> 5 votes

# Answer
# 05AB1E, ~~20~~ 12 bytes

Based on the observation that all outputs can be created by having each row as all 1's or all 0's. Check out AZTECCO's answer, which got there an hour earlier.

```
1ÝIã.ΔƶOQ}ā×

```

Try it online!

```
1Ý            # push the range [0..1] == [0, 1]
  Iã          # raise this to the first input (w) cartesian power
              # this yields all w-tuples of 1's and 0's
    .Δ   }    # find the first that satisfies:
      ƶ       #   each value multiplied by its 1-based index
       O      #   take the sum of that
        Q     #   is equal to the second input (n)
          ā   # push the range [1..len(value)] == [1..w]
           ×  # repeat each digit in the select tuple that number of times

```

---

Alternative 12 byters (Both find a subset of `[1..w]` that sums to `n` and build the triangle from that):

```
L©æ.ΔOQ}®å®×

```

Try it online!

```
LDæIÅœÃнsåā×

```

Try it online!
> 4 votes

# Answer
# Charcoal, ~~48~~ ~~40~~ 28 bytes

```
ＮηＦ⮌…·¹Ｎ«Ｇ↘↖ιＩ¬‹ηι↓¿¬‹ηι≧⁻ιη

```

Try it online! Link is to verbose version of code. Takes arguments in the order `n`, `w`. Explanation: Port of @AZTECCO's answer.

```
Ｎη

```

Input `n`.

```
Ｆ⮌…·¹Ｎ«

```

Count from `w` down to `1`.

```
Ｇ↘↖ιＩ¬‹ηι↓

```

Output a line of `1`s or `0`s depending on whether `n` is big enough.

```
¿¬‹ηι≧⁻ιη

```

Reduce `n` accordingly.

Previous 40 byte answer:

```
ＮθＦＮ⊞υ¹Ｅθ⭆Ｅ⌊⟦⊕ι⁻θι⟧‹⁺ιλ⊖θ∧›№υ¹λ⊟Ｅ⊕λ⊟υ‖Ｏ↘

```

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

```
Ｎθ

```

Input `w`.

```
ＦＮ⊞υ¹

```

Input `n` and make a list of that many `1`s.

```
Ｅθ

```

Start drawing a triangle of height `w`.

```
⭆Ｅ⌊⟦⊕ι⁻θι⟧

```

Draw the upper left half of the triangle.

```
‹⁺ιλ⊖θ

```

Calculate whether this square lies on the diagonal or not.

```
∧›№υ¹λ⊟Ｅ⊕λ⊟υ

```

If `n` is large enough to need both this square and its reflection, then reduce `n` accordingly and output a `1`, otherwise output a `0`. This always works because the very last square is on the diagonal.

```
‖Ｏ↘

```

Reflect to complete the triangle.
> 3 votes

# Answer
# C (gcc), 62 bytes

```
f(w,n,c){for(c=n>=w,w&&f(w-1,n-w*c);~w;putchar(w--?48+c:10));}

```

Try it online!
> 2 votes

# Answer
# Jelly, 13 bytes

```
ŒPS=¥ƇḢċ⁹xɗⱮ⁸

```

Try it online!

A dyadic link taking `w` as its left argument and `n` as it’s right. Returns a list of lists of 0s and 1s. Based on the observation by @AZTECCO and @ovs that we can compose this solely of rows of 0s and 1s so be sure to upvote their answers too!
> 2 votes

# Answer
# , 33 bytes

```
((]echo@#>:)]0>.<:@],~[-]*>:)/^:_

```

Try it online!

A function whose output (rather than return value) prints what we want.
> 2 votes

# Answer
# Vyxal `r`, ~~18~~ 16 bytes

```
⅛ɾṘƛ¼:n≤:Sn*,[-⅛

```

Try it Online!

```
⅛                # (Implicit input) Push to global array
 ɾṘ              # (Implicit input) range(1,n+1) reversed
   ƛ             # Foreach [n]
    ¼:           # Push from global array and duplicate [n,r,r]
      n≤         # Push n and check if r >= n [n,r,b]
        :Sn*,    # Duplicate, coerce to string (0 or 1), multi by n and output.
             [   # If ToS is truthy (r >= n) [n,r]
              -  # Subtract [r-n] (r flag reverses arguments)
               ⅛ # Push to global array.

```

Due to a bug with redefining the register inside a lambda, I'm forced to use the global array. It works well though, and I don't think it'd be any more golfable if the register worked properly.

Based on the insight that everything can be made of rows of 1s and 0s.
> 2 votes

# Answer
# , 54 bytes

```
function(w,n)for(i in w:1){show(1:i&(a=n>=i));n=n-i*a}

```

Try it online!

Using `TRUE` and `FALSE` as the values.
> 1 votes

---
Tags: code-golf, array, open-ended-function
---