# Make your code error, but only sometimes!

Your task is to create a program or function which randomly errors. Specifically, there must be a nonzero probability of erroring, but also a nonzero probability of running without error.

An error is anything that causes a program to terminate abnormally, such as dividing by zero or using an uninitialized variable. This also includes runtime errors, syntax errors and errors while compiling. Statements which manually throw an error, such as JavaScript's throw are allowed.

This program doesn't need to do anything if it doesn't error, other than exiting gracefully.

This is , so shortest answer per language wins.

Note: For this challenge, "randomly" follows the current consensus (so no using undefined behavior or uninitialized memory for randomness), and the program must be capable of producing both outputs if run or compiled multiple times (so a random number with the same seed is not valid)

• I think it's a boring challenge. A lot of the answers are doing basically the same thing and there's little room for golfing. Note that downvotes don't necessarily indicate a challenge is ill-specified -- there's close votes for that.
– xnor
Apr 10, 2020 at 15:43
• Separately, I'm not so sure it's clear, since two of the upvoted answers rely on the state of memory when the program starts, despite the question in my earlier comment.
– xnor
Apr 10, 2020 at 15:45
• I don't really think the current definition of random, although settled, is really clear. For example, the python answer and the brainfuck answer below uses some degree of undefined behavior. The c answer, although fits that definition, won't really crash because of the lack of srand. So, I don't really like challenges based on such loose definitions (and when such definition matters a lot). I would change it to upvote if the question is updated, say, to, the program may or may not crash after a rerun/recompile. Apr 10, 2020 at 15:47
• It seems like so many users are posting 1/(random integer) here... Apr 11, 2020 at 1:33
• @xnor: agreed, this turns out to be somewhat interesting in some assembly languages, but most high level languages make unpredictable behaviour intentionally difficult other than integer division, or a few other things where 0 is special. Apr 11, 2020 at 4:40

# Baby Language, 0 bytes

Try it online!

I knew this could be fun with a non-deterministic tarpit! I looked through the category on the Esolang wiki and found this language...

From the page:

A Baby Language interpreter ignores the input program and does something random. (Likewise, a Baby Language compiler generates a random executable.) As such, whatever you wanted your program to do, there's an (admittedly small) chance that it will actually do it.

The intended use case for the language is to run your program repeatedly until it does what you want. Just like trying to reason with a real baby, this may take quite a while.

So the blank program, and every program for that matter, executes a random program which will therefore randomly error!

I used Esolang user Enoua5's source code which generates and executes a random brainfuck program. It's linked on the Esolang page:

An interpreter created in Python 3 by User:Enoua5: View Source

So the TIO link above takes you to Python 3 interpreter is implemented in the header and the actual (blank) code is in the (blank) code slot, which is ignored anyway!

The above interpreter is simply copied and pasted into the header; a multiline comment starting/ending in the header/footer nullifies the actual code.

• I was shocked when I realized that such a boring language was created by Ais523...
– user92069
Apr 11, 2020 at 3:09
• ais523 is one of the more well-known esolang and code golf folks. I don't know if he's the most well-known, but I can't think of another one who's more well-known. Apr 11, 2020 at 3:39
• I'd say Dennis is more well known Apr 11, 2020 at 5:08
• I keep trying to run it, but all the random program does is factor RSA primes in polynomial time. Apr 11, 2020 at 13:54
• Best comment ever! And we'll never now what it's running... Apr 12, 2020 at 1:00

# Charcoal, 2 bytes

‽‽


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

 ‽  Random value (defaults to 0 or 1)
‽   Random element from implicit range


If the first random value is 1, then the implicit range is simply [0], so the random element is just 0, which does nothing (it's implicitly printed, but printing 0 has no effect).

If the first random value is 0 however, then the implicit range is []. This is an illegal input to randrange which therefore throws a ValueError.

# Bash + Unix utilities, 1211 8 bytes

m$RANDOM  Try it online! If $RANDOM happens to have the value 4, this will run the macro processor m4 (which exits right away on TIO because stdin is empty). If $RANDOM has any other value, you'll get an error because there's no program available via$PATH with the indicated name.

If you want pure bash, with no external utilities, then the shortest I’ve found is my first version (which is 12 bytes long):

((1/RANDOM))

• Hooray, an interesting one. :) Apr 20, 2020 at 6:23

# Python 3, 1514 11 bytes

-3 bytes thanks to @newbie!

1/(id(0)%3)


Try it online!

Also 11 bytes:

id(0)%3or a


Try it online!

How: The id of an object varies across different runs. Thus id(0)%3 can be 0, which causes ZeroDivisionError and NameError in the programs above respectively.

• is it possible for an id to be 0? Apr 11, 2020 at 6:55
• @CommandMaster This is very iffy here since id is implementation dependent. In CPython, id is the address of an object in memory, so it's probably can't be zero. I've read somewhere that most Python implementations randomize the starting address of the stack/data to prevent some sort of attack, which is the behavior being used here. But can't find any documentation on this at the moment. Apr 11, 2020 at 7:06
• @SurculoseSputum: Python itself doesn't have to randomize addresses; OSes do ASLR of at least the stack, and often also static code/data if possible. (e.g. on GNU/Linux that requires a PIE (Position Independent Executable) which is why distros now configure gcc with that as the default.) e.g. if you wrote a C program that did printf("%p\n", main) to print the address of main when you run it, you'd see a different address each run. Unless you compile with gcc -fno-pie -no-pie. related: 32-bit absolute addresses no longer allowed in x86-64 Linux? Apr 12, 2020 at 16:20
• ASLR = en.wikipedia.org/wiki/Address_space_layout_randomization. It's a security feature so exploits like buffer overflows don't know a fixed address to overwrite a return value with. Unless they can get the target of the attack to "leak" a pointer somehow first. (Non-executable stacks defeat code injection via returning to the address of the stack, but other attacks like "returning" to the address of system() in libc with a pointer to "/bin/sh" in the right register would still work if an attacker knew that address.) Apr 12, 2020 at 16:21
• Techniques like that are the basis of so-called ROP attacks - return-oriented programming. Finding little snippets of machine code ("gadgets") at fixed addresses can let you chain together a sequence of return values to eventually make something happen. All of this is much harder to actually exploit if addresses are randomized, instead of identical on every server running the same version of some software. Ok, that should be enough for anyone to google more if they're curious :P Apr 12, 2020 at 16:28

includes 3 different answers, smallest first

# x86-64 machine code "function", 4 bytes

("works" in all 3 modes: 16-bit, 32-bit, and 64-bit. In other modes, FE 00 is a jmp to eax or ax.)

0000000000401000 <timejump>:
401000:       0f 31           rdtsc           # EDX:EAX = timestamp counter
401002:       ff e0           jmp    rax      # "return" with jmp to register


This function can be called with jmp instead of call; it doesn't need you to pass it a return address on the stack. It uses the low 32 bits of the time counter as a jump target, which might or might not be the correct return address (or somewhere else useful).

The crash possibility is code-fetch from an unmapped or non-executable page, or jumping to instructions that fault (e.g. 00 00 add [rax],al), or to an illegal instruction, like a 1F or other byte somewhere in 64-bit mode, or a multi-byte illegal sequence in 16 or 32-bit mode, that will raise #UD.

RDTSC sets EDX:EAX = the number of reference cycles since power-on (i.e. the TSC = TimeStamp Counter, SO canonical Q&A about it. Note that it doesn't count core clock cycles on modern x86). The reference frequency is normally close to the CPU's sticker frequency (e.g. 4008MHz on a nominally 4GHz i7-6700k) so the low 32 bits wraps around in just over 1 second, which is close enough to random for interactive use. Or every few seconds on chips with lower "base" frequencies.

Assuming a valid return address or other jump target exists in the low 32 bits of virtual address space, we have a 1 in 2^32-1 chance of reaching it. Or higher if there are multiple useful targets to dispatch to. (Assuming TSC is uniformly distributed, and fine-grained enough that every 32-bit low half is actually possible. I think this is the case.)

In 32 and 16-bit mode, every possible address (in the same code segment) is reachable, but 64-bit mode unfortunately still splits the TSC between EDX and EAX so most of the 64-bit (or 48-bit) address space is unreachable.

On systems like MacOS where 64-bit processes normally have all their code outside the low 4GiB of address space, use 32-bit mode. Linux non-PIE executables are mapped in the low 2GiB of virtual address space so any non-library code will be reachable.

# x86 32-bit machine code function, 5 bytes

0000000000401000 <inctime>:
8049000:       0f 31                   rdtsc           # EDX:EAX = timestamp counter
8049002:       40                      inc    eax      # EAX++
8049003:       ce                      into            # trap if OF==1
8049004:       c3                      ret


On most x86 CPUs, the TSC is fine-grained and really can be any value in the low half, including 231-1. So incrementing it can produce signed integer overflow, setting OF.

Also works in 16-bit mode (incrementing only AX with this machine code), but not 64-bit mode where into isn't a valid opcode.

# x86-64 machine code function, 6 bytes

(same machine code works in all 3 modes, using the default operand size for the mode; 16, 32, and 32.)

divides 64-bit user input by a random number: can overflow or divide by 0.

0000000000401000 <divrandom>:                          # input in EDX and EAX
401000:       0f c7 f1                rdrand ecx
401003:       f7 f1                   div    ecx       # return EDX:EAX / ECX
401005:       c3                      ret


Yup, x86 has a true RNG built in (Intel since IvyBridge, and AMD since at least Zen).

x86 division of 64-bit EDX:EAX / 32-bit ECX => 32-bit quotient and remainder faults (with a #DE exception -> SIGFPE or other OS signal) if the quotient doesn't fit in 32-bit EAX. With a small dividend, this can only happen on divisor = 0, 1 chance in 2^32.

With function input in EDX:EAX above 2^32-1, small divisors could leave a quotient larger than 2^32-1. So the chance of faulting depends on the input value. Specifically, division runs without faulting if ECX > EDX, where ECX is the random divisor and EDX is the high half of the 64-bit input.

rdrand always sets OF to 0 so we can't use 1-byte into conditionally trap on overflow. (It only sets CF = success, 0 means HW RNG temporarily exhausted).

I can't think of any "unpredictable / undefined behaviour" situation that could actually give different results on different runs, other than meltdown-style timing that depends on microarchitectural conditions.

Some old ARM and MIPS CPUs have unpredictable behaviour that depends on timing if you for example use a multiply where the destination is one of the inputs, or on MIPS I read the result of a load in the next instruction (in the load delay slot). So for example on MIPS lw $ra, ($a0) ; jr $ra (4 bytes each) might use the original return address in $ra (the link register) if the load hits in cache, otherwise it stalls and we'd return to wherever the load points.

• That's cool but I think only the last one is valid. The rest rely on "undefined behavior", so to speak. Apr 11, 2020 at 13:51
• @S.S.Anne: I don't see anything "undefined" in the C UB sense of the word. My source of run-dependent behaviour is a well-defined fast fine-grained counter. I'm not getting "random" data from reading uninitialized memory or something that Intel's manual say is an "undefined" result (like bsf reg,reg with reg=0) but which is actually the same every time on real hardware. That's what the question wording is excluding, I think. I'm fairly confident that on at least some implementations, the TSC can have a low half of 0x7FFFFFFF, or that it can be whatever return address the caller wanted. Apr 11, 2020 at 14:03
• @S.S.Anne, sampling a high-frequency counter at an arbitrary time is a perfectly valid source of randomness -- a number of hardware random number generators do exactly that.
– Mark
Apr 12, 2020 at 7:02
• So it turns out if you read the result register in the load delay slot it's actually well defined. It reads the previous value. The reason this is unpredictable is the CPU doesn't unwind on interrupt so unless you turned interrupts off the value is trashed. So yeah, outside of an interrupt handler it doesn't work. Jan 16 at 19:28
• @Joshua: Oh, so a cache-miss load on R2000 doesn't stall until after running the load-delay instruction? Hmm, what about an I-cache miss after the load, before the delay slot? (Maybe I was mis-remembering or mis-interpreting something I'd read about cache misses, if the source I got this from was correct at all). You're saying it's well-defined and guaranteed to still let the next instruction read the old value, even with I-cache or D-cache misses, as long as there's no interrupt? Do you have a link I can add to this and/or other answers if/when I fix this claim I've repeated? Jan 16 at 20:00

# ><>, 3 bytes

x,;


Try it online!

My first submission in ><>, very simple

# JavaScript (V8), 15 13 bytes

idea and -2 bytes from @apsillers

Uses new Date instead of Math.random, has a $$\\frac{1}{9}\$$ chance of not erroring:

new Date%9&&a


Try it online!

# JavaScript (V8), 17 16 bytes

-1 thanks to @newbie

Math.random()&&a


Try it online!

This has a $$\\frac{1}{2^{1074}}\$$ chance of not erroring, as Math.random() can occasionally be 0.

• stretching the definition of "non-zero probability" Apr 10, 2020 at 23:07
• It would be interesting to see V8's implementation of Math.random and a demonstration that it really is possible for the result to be 0.0. Apr 11, 2020 at 3:55
• @TannerSwett If it was impossible for it to be 0.0, it wouldn't be following the spec, which says the result should be in the range of [0, 1) Apr 11, 2020 at 4:10
• @GrandOpener - Incorrect. It very much specifies that. It specifies that all values along that range (which includes 0) must have roughly equal probability of being output. So yes...it must be capable of returning 0. Apr 13, 2020 at 14:26
• new Date%9&&a is shorter by three characters (Date can be called as a no-parens constructor and Date objects are generally math'ed as numeric timestamps) and meets the community consensus that single-use modulo-time is generally acceptable as a random number source Apr 13, 2020 at 17:42

# J, 6 byte function

z^:?@2


Try it online!

If y is the argument, z^:v conditionally returns the result z y if v y returns 1. Otherwise it returns y unchanged.

? 2 will return 0 half the time and 1 half the time.

No matter what argument we pass to this function, it will be converted into the constant 2 and then passed to z^:?.

So half time the result will be 2, and half the time it will error when trying to execute the non-existent verb z.

## alternative full programs

Though these may look like snippets they should count as full programs in the context of this challenge.

4 bytes thanks to Bubbler:

q:?2


0^.?2

• Wouldn't 0^.?2 work?
Aug 13, 2021 at 5:12
• My first instinct was that that was a snippet, but on 2nd thought it probably counts as a valid program. Aug 13, 2021 at 5:49
• q:?2 also works (q:0 is a domain error). Aug 13, 2021 at 6:17

# Python <= 3.7, 25 24 bytes

lambda x:id(x.__dir__)

Included for its weirdness rather than its brevity. This will cause a segmentation fault in obscure cases involving deep recursion. A fix is being applied, but only to python versions >=3.8.

The crash only occurs on cleanup when exiting the interpreter, but an example of how to call this function (and reproduce the segfault) can be found here: Try it online!

• Welcome to Code Golf, and nice first answer! The question doesn't involve taking any input, so I'm not sure how to call your function? Could you include a Try it online! link to demonstrate? Aug 13, 2021 at 13:46
• Thank you, have edited my answer — please let me know if there are any other community guidelines I'm missing! Aug 13, 2021 at 13:57

# Lost -A, 9 bytes (Probability 1/2)

\\\\
%1-@


As an introduction to Lost for anyone unfamiliar, Lost is a 2-D programming language in which the start location and direction are selected at random at the beginning of the program. This source of randomness is what we use in this challenge.

We want some start locations that will cause an error and some that will not.

The program will error if it starts on the character % going right (or down). In this case it will encounter the ops %1-@ before termination. This pushes -1 and exits. Since -1 is not a valid character code this causes an error in character mode.

The program will terminate safely if it starts on the character % going left (or up). In this case it will encounter the ops %@ before termination. This does nothing and exits.

Since we have a path that errors and one that does not, all that remains is to know that every path terminates, which is guarenteed by the \\\\. So this program is valid.

We could shorten this significantly if there was not a termination requirement. The program :

%1-@


Try it online!

Either errors, terminates cleanly or loops forever, and it selects which at random with the following probabilities:

• 1/2 Non-terminating

• 1/4 Errors

• 1/4 Terminates cleanly

1: For verification we turn off character mode. All outputs containing negative numbers are the ones that will error in character mode.

• Could this be golfed by erroring through running out of memory? May 19 at 10:07
• @emanresuA I mean %1@ should eventually run out of memory. (Probably, I ran it for like 10 minutes and it didn't crash, it should be allocating new memory but it would take a very long time to crash anyway) However I don't think this is allowed. May 19 at 11:06
• My interpretation of that rule is that you can't simultaneously assume unlimited memory and assume finite memory (or similar) however since this program doesn't have to handle any input it's perfectly fine to have it push 1s until it runs out. May 19 at 11:08

# APL (Dyalog Unicode), 3 bytes

÷?2


Try it online!

(Requires IO←0)

Inverse of random boolean (any range including 0 would work). I expect this'll be a common technique...

÷    ⍝ Inverse
?2  ⍝ Random number in [0,1]


# PowerShell, 10 bytes

1/(random)


Try it online!

get-random returns an int between 0 and 0x7FFFFFFF so it'll eventually divide by 0. Maybe...

# INTERCAL, 10 bytes

DO%9GIVEUP


The only way to terminate an INTERCAL program without an error is to execute a GIVE UP statement -- running off the end of the source code is a runtime error. This program uses INTERCAL's probabilistic execution feature to have a 9% chance of successfully exiting; the rest of the time, it errors out:

ICL129I PROGRAM HAS GOTTEN LOST
ON THE WAY TO WHO KNOWS WHERE
CORRECT SOURCE AND RESUBNIT

• Is this a serious programming language? How old is it? Apr 10, 2020 at 23:47
• @S.S.Anne, INTERCAL was one of the first, if not the first, esoteric programming languages, having been created in 1972 as a parody of various programming languages in use at the time.
– Mark
Apr 10, 2020 at 23:50

# ><>, 5 bytes

v
x+;


Try it online!

## Explanation

The pointer will be represented by a hashtag symbol. It will replace in bewteen these spaces:

v
x + ;


Ok, explanation start.

The instruction pointer goes down.

v*
x + ;


The step is randomized.

v
x*+ ;


Case 1: Error

v
x +*;


It tries to pop two items, but there is nothing on the stack. Cue error.

Case 2: Exit gracefully

v
x + ;*


It loops to the right side, and ends on the semicolon.

• Why not just x+; for 3 bytes?
– cole
Apr 11, 2020 at 9:08
• I think it only goes perpendicular. Apr 11, 2020 at 10:22
• I’m not sure what you mean by that, but it appears another ><> answer in this thread has done that 3 byter (well, something tantamount to it).
– cole
Apr 11, 2020 at 10:44

# C (gcc), 17 16 bytes

Random across function calls.

Saved a byte thanks to newbie!!!

f(i){i/=rand();}


Try it online!

Has a $$\\frac1{\text{RAND_MAX} + 1}\$$ chance of failing with Floating point exception.

Random across runs.

# C (gcc), 19 bytes

f(i){i/=(int)&i%3;}


Try it online!

• i;f() => f(i) Apr 10, 2020 at 14:28
• Why is it necessary do i/= rather than i/? Does the compiler optimize away the expression as useless otherwise?
– xnor
Apr 10, 2020 at 14:37
• @xnor Yup, the compiler simply chucks the code away as dead-code. Apr 10, 2020 at 16:26
• "so a random number with the same seed is not valid" Apr 10, 2020 at 23:42
• @S.S.Anne: I think we can justify this because it's a function not a program. If called multiple times, it will generate new random numbers and update the seed, not reusing the same seed for every call. p.s. I posted an x86 machine code answer to this which you might find interesting. My first idea was div by rdrand, but came up with some less boring stuff. Apr 11, 2020 at 4:31

=0/RAND(


Google will a closing parentheses automatically to give =0/RAND().

Since RAND() produces a uniformly random between 0 inclusive and 1 exclusive and to 15 decimal points of accuracy, is has a 0.0000000000001% chance of returning exactly 0 and causing the #DIV/0! error.

# Metatape, 4 3 bytes

x?(


-1 byte thanks to Hactar, the language creator, on Discord

Initially, the tape head is within a tape and pointing to a null cell. The command x exits the current cell, creating a new tape and putting the initial tape within it. Now the tape head is within a tape and pointing at a tape.

The ? command then generates a random bit, setting the current cell of the tape to null if it is 0 and doing nothing if it is 1. Then the ( command jumps to the next | or ) characters in the code if and only if the current cell is null, and does nothing otherwise. Thus, if the bit generated by ? is 0, the interpreter will throw an error, as there is no | or ) to jump to. On the other hand, Metatape does not implicitly check for every ( matching with a ), so if the bit generated by ? is 1, no error will be thrown.

EDIT: After further clarification with the language's creator, I found that the last sentence I wrote may not apply to all interpreters, and thus this answer might not work for all interpreters. Oops.

# Z80 machine code, 6 5 bytes

I finally managed to reduce it to 5 bytes and also make it more well-behaved at the same time:

ED 5F B7 C0 76


Explanation:

ED 5F   LD A, R  ; get non-deterministic value (00-7F) from memory refresh register
B7      OR A, A  ; set Z flag if A is zero
C0      RET NZ   ; return normally, unless we were unlucky and got zero
76      HALT     ; halt the CPU


Alternatively to the HALT instruction RST could be used to call an error handler.

Other approaches that use 6 bytes and fail in a less well-behaved way:

ED 5F 17 32 06 00


Explanation:

ED 5F      LD A, R       ; get random value (00-7F) from refresh count register
17         RLA           ; rotate left one
32 06 00   LD (0006), A  ; write the byte immediately following this instruction.


There is a chance that this results in one of the conditional RET instructions to be written after the code, which returns normally if the condition happens to be met, which is the case for RET NZ (C0), RET NC (D0), RET PE (E8) and RET M (F8). Otherwise, a random instruction is executed and the program counter runs into whatever is in RAM after that, failing horribly. If bit 8 of the R register was somehow set (which doesn't normally happen), or any instruction with an opcode up to 7F would somehow end the program normally, this could be reduced to 5 bytes. The address operand in the last instruction must be set relative to where the code is actually located.

ED 5F B7 28 FE C9


Explanation:

ED 5F   LD A, R  ; get non-deterministic value (00-7F) from memory refresh register
B7      OR A, A  ; set Z flag if A is zero
28 FE   JR Z, -2 ; infinite loop if Z-flag is set
C9      RET      ; return


An infinite loop might not really count as an 'error' though. An alternative solution (same length), inspired by Peter Cordes' x86 solution, is to mess with the return address:

E5 ED 5F AC 67 E9


Explanation:

E5      POP HL   ; get return address from stack
ED 5F   LD A, R  ; get non-deterministic value (00-7F) from memory refresh register
AC      XOR A, H ; this will only leave H intact
67      LD H, A  ;       if R was zero by chance

• Welcome to the site. Could you include a copy of the code without comments or extraneous elements? Apr 19, 2020 at 19:32
• sure, like this? Apr 19, 2020 at 19:52
• Yeah that's good. Normally a user won't get a message unless you put an @ before their name in your comment btw. Apr 19, 2020 at 19:55
• @AdHocGarfHunter good to know! Thanks for helping me along :) Apr 19, 2020 at 19:57

# Zsh, 8 7 bytes, $$\ \approx \frac{1}{10}\$$ chance of success

>
<*4

Attempt This Online!

Determines whether the process ID ends in 4.

# Jelly, 5 bytes

I haven't used Jelly for a long time, it's time for me to pick it up again.

2X’İX


Try it online!

# Explanation

2X    Pick random from [    1,  2]
’   Decrement:       [    0,  1]
İ  Reciprocal:      [  inf,  1]
X randrange 1      [Error,  1]


# Octave / MATLAB, 13 bytes

det(0:rand*2)


Try it online!

### How it works

rand produces a random number with uniform distribution between 0 and 1. So the range 0:rand*2 may be 0 (1×1 matrix) or [0 1] (1×2 matrix). det tries to compute the determinant, which is only defined for square matrices.

• Try nan(rand) or inf(rand) in MATLAB for nine bytes which works only for rand values zero and one. In Octave, we can do better with 0(rand) for seven bytes.
– user92857
Apr 11, 2020 at 0:53
• @AravindhKrishnamoorthy Thanks for the suggestion, but rand draws numbers from the open interval (0,1) (both in Matlab and in Octave), so it wouldn't work, would it? Apr 11, 2020 at 1:03
• Oh indeed! Then we've to use randn and waste a byte :(
– user92857
Apr 11, 2020 at 1:13
• @AravindhKrishnamoorthy That works, but it relies on the fact that the ideally continuous random variable is actually discrete, and thus it has some non-zero probability of producing an integer. I say "but" because it's a "dirty" trick, but then golfing is all about that kind of tricks. Anyway, it's a totally different approach, you should post that yourself (and will get my upvote) Apr 11, 2020 at 11:59

# 05AB1E, 4 bytes

Î)ΩE


Try it online!

Î        Push 0 and input, ie. [0, ""] b/c input blank
)       Wrap total stack to an array
Ω      Push random element of a, ie. [0, ""]
E     For-loop in [1 .. a]


where a is the top of the stack

Errors when "" is randomly selected & for loop is attempted on it.
Proceeds when 0 is randomly selected & for loop is attempted on it.

• Is there any single character function that errors with 0 and works with 1? Because then you could replace Î) with T Apr 11, 2020 at 12:43
• I didn't find one @CommandMaster Apr 11, 2020 at 14:04
• 3 bytes: ®ΩE. ® pushes -1 by default, and then the Ω choses either - or 1 Apr 20, 2020 at 10:46

# SQL (Oracle), 3733 Bytes

SELECT 1/INSTR(UID,3) FROM DUAL;


Fails if the User Session doesn't have a 3 in it. Edit: Was using SYSDATE, but UID is shorter. Although I'm kinda sad. I liked having a function that worked in March, but not February.

• Although this answer is interesting, the requirements state it must be random. I'm not very good with SQL, but wouldn't SELECT 1/RAND() work (errors if RAND() is 0, which has a very, very small chance of happening)? Apr 10, 2020 at 19:38
• @RedwolfPrograms RAND isn't a valid function in Oracle.
– Del
Apr 10, 2020 at 19:39
• I have not used oracle for ages. But would the work instead ? x int:=1/INSTR(UID,3) Apr 11, 2020 at 13:10

# R, 15 14 bytes

if(rexp(1)>1)a


Try it online!

R doesn't throw errors often. In particular, dividing by 0 doesn't lead to an error (1/0=Inf); nor does attempting to access an out-of-bounds entry in a vector (outputs NA with a warning). Two easy ways to get an error are: 1. an if statement gives an error if it is not fed a TRUE/FALSE value; 2. trying to access a non-existing object.

Here, if the random variate is >1, we try to access a which doesn't exist, so R throws Error: object 'a' not found. If the random variate is <1, nothing happens.

Previous version:

# R, 15 bytes

if(T[rexp(1)])1


Try it online!

Here, rexp(1) generates a realization of the exponential distribution, i.e. a random value $$\x\in\mathbb R_+\$$.

• if $$\x<1\$$ then T[x] is an empty logical vector and R throws an Error: argument is of length zero
• if $$\1\leq x<2\$$ then T[x] is TRUE and R outputs 1 without error
• if $$\2\leq x\$$ then T[x] is NA and R throws an Error: missing value where TRUE/FALSE needed

An error is thrown with probability $$\1-e^{-1}+e^{-2}\approx 0.767\$$.

## Compiled Stax, 28 27 25 bytes

Requires 116 TB RAM, and ulimit -s set to 116TB.

8000000000000{1-cy{}?}Y!


At present time, obvious ways to golf this fail to compile due to the compiler not supporting the requisite language feature.

This program attempts a recursive block invocation with a depth of 8000000000000, which in turn tries to create 8000000000000 16 byte stack frames on the runtime stack. This either succeeds or fails with probability of about .5 depending on how far apart the program and the top of the stack are in address space are.

I am using the environment's RNG that is actually documented to be random to make this fault or not fault.

And recursive said there's no such thing as nondetermistic stax.

• @RedwolfPrograms: But it is random. The top-of-the-stack address is documented to be randomized. Apr 12, 2020 at 23:32
• Oh, sorry. I'm just used to people not reading the spec and posting answers that abuse undefined behavior. Nice answer! Apr 12, 2020 at 23:34

# Taxi, 209 bytes

Go to Heisenberg's:w 1 r 3 r 1 l.Pickup a passenger going to Magic Eight.Pickup a passenger going to Magic Eight.Go to Magic Eight:s 1 r 1 l 3 r.Pickup a passenger going to Cyclone.Go to Taxi Garage:e 2 l 2 r.


Try it online!

Ungolfed and commented:

[ Heisenberg's produces random integers ]
Go to Heisenberg's:w 1 r 3 r 1 l.
[ Pickup two random integers ]
Pickup a passenger going to Magic Eight.
Pickup a passenger going to Magic Eight.
[ Magic Eight compares two numeric passengers ]
[ It returns the first passenger if it is less than the second and no one if it is not ]
Go to Magic Eight:s 1 r 1 l 3 r.
[ Try to pickup a passenger, which will error if there isn't anyone waiting ]
Pickup a passenger going to Cyclone.
[ Return to the garage to avoid getting the "you're fired" error ]
Go to Taxi Garage:e 2 l 2 r.


Try the ungolfed and commented version online!

# Knight, 3 bytes

/1R


Try it online!

Has a roughly $$\\frac{1}{65536}\$$ chance of dividing by zero.

The classic 1/rand() trick. Assumes that dividing by zero throws an error, of course.

Uncommenting the line at the top of the header code will srand with a seed that will cause glibc's rand() to return 0xe7d0000, which when masked by 0xFFFF, results in 0.

><>, 4 bytes

The ! skips the next instruction, even if it would give an error. The x set the pointer's direction to a random direction. It can make it go up or down but if the pointer reaches the edge then it wraps around. The ; ends the program. The { can be replaced with any character as long as it's not a valid command in ><>.

!{x;


https://tio.run/##S8sszvj/X7G6wvr/fwA Try it online!

• Welcome to the site! x;{ does the same thing using the wrapping. Aug 15, 2021 at 11:07
• what language is this? brainf?
– mekb
Aug 20, 2021 at 6:44

# C (clang), 24 bytes

main(i){i/=(time(0)%3);}


Try it online!

# C, 20 bytes

main(i){i/=time(0);};


Will crash once every +/- 68 years.

https://en.wikipedia.org/wiki/Year_2038_problem

# Wolfram Language (Mathematica), 17 bytes

1/RandomInteger[]


Try it online!