10
\$\begingroup\$

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)

\$\endgroup\$
  • 14
    \$\begingroup\$ 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. \$\endgroup\$ – xnor Apr 10 at 15:43
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – xnor Apr 10 at 15:45
  • 4
    \$\begingroup\$ 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. \$\endgroup\$ – newbie Apr 10 at 15:47
  • 2
    \$\begingroup\$ It seems like so many users are posting 1/(random integer) here... \$\endgroup\$ – Scratch---Cat Apr 11 at 1:33
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – Peter Cordes Apr 11 at 4:40

38 Answers 38

26
\$\begingroup\$

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!


Details on TIO link

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.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ I was shocked when I realized that such a boring language was created by Ais523... \$\endgroup\$ – user92069 Apr 11 at 3:09
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Tanner Swett Apr 11 at 3:39
  • 2
    \$\begingroup\$ I'd say Dennis is more well known \$\endgroup\$ – Lyxal Apr 11 at 5:08
  • 20
    \$\begingroup\$ I keep trying to run it, but all the random program does is factor RSA primes in polynomial time. \$\endgroup\$ – Redwolf Programs Apr 11 at 13:54
  • 1
    \$\begingroup\$ @Lyxal And Martin Ender, and James, and Mego \$\endgroup\$ – HighlyRadioactive Aug 3 at 0:49
17
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
12
\$\begingroup\$

Python 3, 15 14 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.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ -3byte: 1/(id(0)%3) \$\endgroup\$ – newbie Apr 10 at 15:01
  • 1
    \$\begingroup\$ is it possible for an id to be 0? \$\endgroup\$ – Command Master Apr 11 at 6:55
  • 3
    \$\begingroup\$ @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. \$\endgroup\$ – Surculose Sputum Apr 11 at 7:06
  • 1
    \$\begingroup\$ @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? \$\endgroup\$ – Peter Cordes Apr 12 at 16:20
  • 1
    \$\begingroup\$ 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.) \$\endgroup\$ – Peter Cordes Apr 12 at 16:21
12
\$\begingroup\$

Bash + Unix utilities, 12 11 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))
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Hooray, an interesting one. :) \$\endgroup\$ – Steve Bennett Apr 20 at 6:23
10
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ That's cool but I think only the last one is valid. The rest rely on "undefined behavior", so to speak. \$\endgroup\$ – S.S. Anne Apr 11 at 13:51
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – Peter Cordes Apr 11 at 14:03
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – Mark Apr 12 at 7:02
7
\$\begingroup\$

><>, 3 bytes

x,;

Try it online!

My first submission in ><>, very simple

| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

J, 6 bytes

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.

| improve this answer | |
\$\endgroup\$
5
\$\begingroup\$

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

\\\\
%1-@

Try it online! Verification1

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.

| improve this answer | |
\$\endgroup\$
5
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • 8
    \$\begingroup\$ stretching the definition of "non-zero probability" \$\endgroup\$ – aaaaa says reinstate Monica Apr 10 at 23:07
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Tanner Swett Apr 11 at 3:55
  • 1
    \$\begingroup\$ @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) \$\endgroup\$ – Redwolf Programs Apr 11 at 4:10
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – Jimbo Jonny Apr 13 at 14:26
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ – apsillers Apr 13 at 17:42
4
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Why not just x+; for 3 bytes? \$\endgroup\$ – cole Apr 11 at 9:08
  • \$\begingroup\$ I think it only goes perpendicular. \$\endgroup\$ – PkmnQ Apr 11 at 10:22
  • \$\begingroup\$ 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). \$\endgroup\$ – cole Apr 11 at 10:44
4
\$\begingroup\$

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!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ i;f() => f(i) \$\endgroup\$ – newbie Apr 10 at 14:28
  • \$\begingroup\$ @newbie Nice one - thanks! :-) \$\endgroup\$ – Noodle9 Apr 10 at 14:32
  • \$\begingroup\$ Why is it necessary do i/= rather than i/? Does the compiler optimize away the expression as useless otherwise? \$\endgroup\$ – xnor Apr 10 at 14:37
  • 1
    \$\begingroup\$ "so a random number with the same seed is not valid" \$\endgroup\$ – S.S. Anne Apr 10 at 23:42
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – Peter Cordes Apr 11 at 4:31
4
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

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]
| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

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.

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

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

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ @RedwolfPrograms: But it is random. The top-of-the-stack address is documented to be randomized. \$\endgroup\$ – Joshua Apr 12 at 23:32
  • \$\begingroup\$ Oh, sorry. I'm just used to people not reading the spec and posting answers that abuse undefined behavior. Nice answer! \$\endgroup\$ – Redwolf Programs Apr 12 at 23:34
3
\$\begingroup\$

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
E9      JP HL    ; jump to (probably broken) return address
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Welcome to the site. Could you include a copy of the code without comments or extraneous elements? \$\endgroup\$ – Ad Hoc Garf Hunter Apr 19 at 19:32
  • \$\begingroup\$ sure, like this? \$\endgroup\$ – Stefan Paul Noack Apr 19 at 19:52
  • \$\begingroup\$ Yeah that's good. Normally a user won't get a message unless you put an @ before their name in your comment btw. \$\endgroup\$ – Ad Hoc Garf Hunter Apr 19 at 19:55
  • \$\begingroup\$ @AdHocGarfHunter good to know! Thanks for helping me along :) \$\endgroup\$ – Stefan Paul Noack Apr 19 at 19:57
2
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – user92857 Apr 11 at 0:53
  • \$\begingroup\$ @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? \$\endgroup\$ – Luis Mendo Apr 11 at 1:03
  • \$\begingroup\$ Oh indeed! Then we've to use randn and waste a byte :( \$\endgroup\$ – user92857 Apr 11 at 1:13
  • \$\begingroup\$ @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) \$\endgroup\$ – Luis Mendo Apr 11 at 11:59
2
\$\begingroup\$

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] 
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Is this a serious programming language? How old is it? \$\endgroup\$ – S.S. Anne Apr 10 at 23:47
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – Mark Apr 10 at 23:50
2
\$\begingroup\$

C (gcc), 28 bytes

f(i){srand(&i);i/=rand()&1;}

Crashes approximately every other time it's run. Abuses ASLR.

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Since we ultimately rely on &i for randomness, why not get rid of the rand stuff? f(i){i/=(int)&i<0;} works. \$\endgroup\$ – Surculose Sputum Apr 11 at 7:28
  • 2
    \$\begingroup\$ @SurculoseSputum Because then it would violate the rules for "randomly". \$\endgroup\$ – S.S. Anne Apr 11 at 13:46
  • 2
    \$\begingroup\$ I just reread the specification - apparently this challenge is much different than I thought... \$\endgroup\$ – Surculose Sputum Apr 11 at 16:04
  • \$\begingroup\$ @SurculoseSputum: I think that's a constant, but such an expression should exist. \$\endgroup\$ – Joshua Apr 24 at 23:00
2
\$\begingroup\$

Pyth, 3 bytes

-1 thanks to FryAmTheEggman.

lO2

Try it online!

| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ Using l is shorter than /1, though there still might be something better. \$\endgroup\$ – FryAmTheEggman Apr 10 at 15:22
2
\$\begingroup\$

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\$.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

PowerShell Windows, 10 bytes

ps(random)

get-random returns an int between 0 and 0x7FFFFFFF so it'll eventually match some PID and ps will get the process that are running on the local computer. Maybe...


PowerShell Linux, 11 bytes

gps(random)

TIO does not work because System.UnauthorizedAccessException. Please use your own Powershell. :)

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Ruby, 9 bytes

1/rand(2)

Try it online!

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ While very concise, I'm not too sure if this approach works: rand returns a Float, but 1 / 0.0 is Infinity, not an exception. (That's at least in Ruby 2.6, the behaviour might be different in older versions.) \$\endgroup\$ – Aaron Christiansen Apr 11 at 11:23
  • \$\begingroup\$ Damn you're right. \$\endgroup\$ – Armand Fardeau Apr 11 at 17:00
2
\$\begingroup\$

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!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Google Sheets, 8 bytes

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

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Batch, 11 bytes

%random:1=%

Has a probability of 1/65536 Corrected by @Neil, 5/32768 (~0.0015%) to not generate an error.

Edit: Alternatively,

%random:~1%
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 5/32768, I think? (1, 11, 111, 1111 and 11111 won't error, and %random% only goes from 0 to 32767.) \$\endgroup\$ – Neil Apr 13 at 13:48
  • \$\begingroup\$ @Neil you're right, will fix that \$\endgroup\$ – HackingAddict1337 Apr 13 at 14:44
1
\$\begingroup\$

Wolfram Language (Mathematica), 17 bytes

1/RandomInteger[]

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

brainfuck, 2 bytes

Sometimes segfaults, sometimes doesn't.

<.

Try it online!

| improve this answer | |
\$\endgroup\$
  • 3
    \$\begingroup\$ Isn't this implementation based, not random? \$\endgroup\$ – Redwolf Programs Apr 10 at 14:27
  • \$\begingroup\$ sometimes malloc allocates a bigger page so you can read something before the tape, and sometimes malloc allocates smaller page so reading something before the tape segfaults \$\endgroup\$ – Szewczyk Apr 10 at 14:28
  • \$\begingroup\$ personally after mashing the run button for a while, I've seen two segfaults so far \$\endgroup\$ – Szewczyk Apr 10 at 14:29
  • \$\begingroup\$ That's just because you're mashing the run button too fast. Also, this uses neither options 1, 2, nor 3 from the meta consensus. \$\endgroup\$ – S.S. Anne Apr 10 at 23:34
  • \$\begingroup\$ +[<[-]+] doesn't segfault on TIO, so I don't think this is valid. In fact, if the [-] is removed, it halts, so the tape is seemingly looped. \$\endgroup\$ – my pronoun is monicareinstate Apr 11 at 3:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.