# Shortest code to produce non-deterministic output

You need to produce output that is non-deterministic.

In this case, this will be defined to mean that the output will not always be the same result.

Rules:

• A pseudo-random number generator that always has the same seed does not count.

• You can rely on the program being run at a different (unknown) time each execution.

• Your code's process id (if it's not fixed by the interpreter) can be assumed to be non-deterministic.

• You may rely on web-based randomness.

• Your code may not take non-empty input. Related meta post.

• The program is not required to halt, but the output must be displayed.

function answersUrl(a){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(a,b){return"https://api.stackexchange.com/2.2/answers/"+b.join(";")+"/comments?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(a){answers.push.apply(answers,a.items),answers_hash=[],answer_ids=[],a.items.forEach(function(a){a.comments=[];var b=+a.share_link.match(/\d+/);answer_ids.push(b),answers_hash[b]=a}),a.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(a){a.items.forEach(function(a){a.owner.user_id===OVERRIDE_USER&&answers_hash[a.post_id].comments.push(a)}),a.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(a){return a.owner.display_name}function process(){var a=[];answers.forEach(function(b){var c=b.body;b.comments.forEach(function(a){OVERRIDE_REG.test(a.body)&&(c="<h1>"+a.body.replace(OVERRIDE_REG,"")+"</h1>")});var d=c.match(SCORE_REG);d?a.push({user:getAuthorName(b),size:+d[2],language:d[1],link:b.share_link}):console.log(c)}),a.sort(function(a,b){var c=a.size,d=b.size;return c-d});var b={},c=1,d=null,e=1;a.forEach(function(a){a.size!=d&&(e=c),d=a.size,++c;var f=jQuery("#answer-template").html();f=f.replace("{{PLACE}}",e+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link),f=jQuery(f),jQuery("#answers").append(f);var g=a.language;g=jQuery("<a>"+g+"</a>").text(),b[g]=b[g]||{lang:a.language,lang_raw:g,user:a.user,size:a.size,link:a.link}});var f=[];for(var g in b)b.hasOwnProperty(g)&&f.push(b[g]);f.sort(function(a,b){return a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase()?1:a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase()?-1:0});for(var h=0;h<f.length;++h){var i=jQuery("#language-template").html(),g=f[h];i=i.replace("{{LANGUAGE}}",g.lang).replace("{{NAME}}",g.user).replace("{{SIZE}}",g.size).replace("{{LINK}}",g.link),i=jQuery(i),jQuery("#languages").append(i)}}var QUESTION_ID=101638,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",OVERRIDE_USER=34718,answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:800}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>

• @mbomb007 In C there are many things that are simply "undefined" behaviour. Any given interpreter is allowed to do whatever it wants in any situation. For all we know, gcc might order you a pizza if you try to overflow a signed integer on a rainy Tuesday, but will make a trout jump out of your screen on all other days. So you wouldn't really ever know if it's actually deterministic or not in any given implementation. – Martin Ender Nov 30 '16 at 20:44
• @MartinEnder I'm not sure if that matters. We define languages here by their implementation, not by the specification (as languages without an implementation is not allowed) – Nathan Merrill Nov 30 '16 at 21:00
• @MartinEnder Yeah, I agree with Nathan. – mbomb007 Nov 30 '16 at 21:01
• Note that undefined behaviour in C often leads to crashes, and crashes on UNIX and Linux lead to core files which contain the process ID inside them. That would seem to comply with the question as currently worded. – user62131 Nov 30 '16 at 21:23
• Unless I misunderstood, the question did not ask for code that takes advantage of undefined behavior. It asks for code that takes advantage of defined behavior to guarantee non-determinism. – WGroleau Dec 1 '16 at 3:30

# CJam, 2 bytes

et

• You can rely on the program being run at a different (unknown) time each execution.

Yeah, that one. et is a single built-in that returns the array [YYYY M D h m s ms W Z], printed as YYYYMDhmsmsWZ.

## Keg, 1 byte

~


This pushes a random number onto the stack and then outputs that number by default.

• Polyglots with Volatile – Lyxal Oct 25 '19 at 22:21
• Volatile doesn't have implicit output. – user85052 Oct 25 '19 at 22:49

Wirefunge - 2 bytes

¿>


¿ - Randomized output every iteration

> - When it rises, puts 1-8 on stdout

## Clojure, 4 bytes

rand


The obvious answer. rand is a core function that returns a floating-point number between 0 and 1 (exclusive) when called without any arguments.

I don't think it gets any shorter than this in Clojure.

# Perl 6, 13 bytes

put Bool.pick


## Marbelous, 5 bytes

FF
??


Prints a single random byte. FF creates a marble with value 255. That marble falls through the random number generator ?? which replaces the marble's value with a random value between 0 and 255 inclusive. When the marble falls off the bottom of the board, it gets printed to STDOUT as a byte.

## R, 7 bytes

The Student t Distribution

rt(1,1)


The Exponential Distribution

rexp(1)


Two options how to generate a random number with the shortest code.

# Thue, 17 bytes

a::=
a::=~1
::=
a


Randomly prints either nothing, or the digit 1.

## T-SQL 15 bytes

print getdate()


# Minkolang v1.5, 4 bytes

lhN.


l pushes 10. h pushes a random integer from 0 to 10, N outputs it and . ends program. Simple, eh?

Try it online!

# Ceylon (on JVM), 22 bytes

()=>system.nanoseconds


This turned out surprisingly difficult. At first I thought I cold use the .hash attribute of all objects (corresponds to Java's .hashCode() when running in the JVM), but it turns out that most objects I can write in a literal way have their .hash attribute overridden, returning a deterministic value.

For example, [] (the empty tuple) or {} (the empty iterable) are both the same object, and which inherits List.hash, which returns 1 in this case. For strings (like ""), characters (c) or numbers (like 3 or 2.5) of course the hash needs to be deterministic, same for true and false (0, 99, 3, 1074003968, 1231, 1237, respectively).

The base class Basic, which has the Java-like hash code implementation (assumedly based on the memory address?) is abstract, so I can't use Basic().hash (nor Object().hash – also abstract, and here even the method is not implemented). So let's create a new class, create an instance and take its hash code?

class E() {}
function f() => E().hash;
shared void run() {
print(f());
}


This always outputs 1116094714 whenever I execute this program. (Adding other statements which allocate memory before the print line changes the result – still deterministically, though.)

Ceylon also supports anonymous classes as object expressions. Those can extend classes or implement interfaces and have own code, but the most minimal variant is just object{}:

shared void run() {
function f() => object{}.hash;
print(f());
}


Still the same result 1116094714, though.

Another idea was to use the hash code of a class or function reference. (Those are normal objects, I thought.) But trying to use run.hash (or f.hash) gives a compiler error:

error: direct function references do not have members

We can work around this by assigning this function reference first to a value, which will create an object of a (hidden) anonymous class:

shared void run() {
value x = run;
value y = run;
print([x.hash, y.hash]);
}


This prints two different values, but the same ones ([762384154, 690052870]) each time I run the program. Still deterministic.

So, using any hash code will not bring us forward (and I suppose that the other JVM answers here with .hashCode() would have the same problem on my JVM implementation). Same with printing an object with the default .string implementation based on .hash.

There is no random number facility in ceylon.language, so using either ceylon.random or Java's java.util.Random (or java.lang.Math.random()) needs an import, which increases the size more than I want to tolerate for a codegolf answer. Here is an example:

import ceylon.random { ... }
shared void run() {
print(randomize{1,2});
}


So let's look at what we have in ceylon.language. There are four top-level objects which allow access to the environment:

• operatingSystem – name, version, path/file separator, newline.
• process – command line arguments, system properties, environment variables, input/output.
• runtime – whether we are on JVM/JS/Dart, version info, and stuff like bit sizes. Nothing which will change between runs of the same program in the same VM.
• system – ah, here we go. Beside locale, character encoding and time zone offset we also have:
• milliseconds
• nanoseconds

Both will change with each call of a program, and the latter one is shorter.

So here we have an anonymous function returning different values:

() => system.nanoseconds


If we want a named function, its definition can look like this:

Object n()=>system.nanoseconds;


(It actually returns Integer, but that is one character longer than Object.)

# Shell, 2 bytes

ps

Explain: the PIDs returned are not going to be the same each time.

# ForceLang, 11 bytes

random.rand


A function that, when called with no arguments, produces a random rational of the form n/2^80, where n is an integer on [0,2^80-1].

(If you give it a positive integer argument m [which must be strictly less than 65536, not that you'll ever reasonably need to go nearly that high] it will produce a random rational of the form n/2^m, where n is an integer on[0,2^m-1])

# SmileBASIC, 6 bytes

?TIME\$


Prints the current time.

# tcl, 3

Must be run on an interactive shell

pwd


Gets the current working directory.

Or alternatively

pid


Gets the current process identifier

Demo: Go to https://www.tutorialspoint.com/execute_tcl_online.php and in the green area, type

tclsh


Then type

pwd


and

pid


## Alice, 4 bytes

2Uo@


Try it online!

Prints a single byte, either 0x00 or 0x01, with 50% probability each.

2    Push 2.
U    Get a random integer in [0,1].
o    Output that integer as a byte.
@    Terminate the program.


# Fourier, 3 bytes

9ro


Outputs a random number from 0 to 9.

Try it online!

# Braingolf, 2 bytes

1r


Pushes 1 to the stack, then pushes a random number between 0 and the last item on the stack (1). Implicitly prints the last item on the stack (the random number)

The most random I could get for 6 bytes

+9  Set the accumulator to 9
R   Set the accumulator to a random integer between 0 and 9
O   Output the result


I could change R to R-9 to double the randomness for 2 extra bytes.

# Taxi, 224 222 bytes

Go to Heisenberg's: w 1 r, 3 r, 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery: s 1 r, 1 l.Pickup a passenger going to Post Office.Go to Post Office: n, 1 l, 1 r.Go to Taxi Garage: n 1 r, 1 l, 1 r.


Prints a random number. The spec does not give any details on what number should be. The last statement can be omitted if you don't mind the code giving an error after printing the output.

• Can you link to the language, since this is not a well-known one? – mbomb007 Jul 29 '17 at 3:30

# Chip, 2 + 3 = 5 bytes

+3 bytes for -w

g?


Gives infinite-length output. Each byte of output is independent, and is either NUL \x00 or '@' \x40.

There are eight equivalent Chip programs that are like this, from a? (which prints \x00 or \x01) to h? (which prints \x00 or \x80). g? is just the most visible option.

For each of these programs, the letter a through h defines the index of a bit of the output, and ? produces a random value to set it to. The two elements may be provided in any order; they must only touch each other on a 2D plane.

Try it online! The TIO includes the -cN flag. This flag is not necessary, but cuts off the program after N bytes. Try without the cutoff if you wish, but TIO's limit is at 128KiB.

# Flobnar, 5 4 bytes

-1 byte thanks to @JoKing

0?.@


Try it online!

# Rust, 28 bytes

fn main(){print!("{:p}",&1)}


Try it online!

Takes a reference to a temporary 1 and prints the address.

# Rust, 17 bytes

fn main(){0-1u8;}


Try it online! (requires the -A const_err compiler flag)

This is a bit sketchier, and I'm not sure whether it counts. The non-deterministic output is to STDERR, and the non-determinism arises only based on the value of an environment variable.

This program attempts to compute 0 - 1, where both integers have type u8 (the default is i32, which won't cause an overflow because it's signed). By default, Rust compiles the file in debug mode, in which arithmetic overflow causes a panic instead of wrapping. When a program panics, it will print a stack trace if the environment variable RUST_BACKTRACE is set to 1, hence the non-determinism.

# Ink, 5 bytes

{~a|}


Try it online!

Either outputs "a" or nothing.

## Perl 6, 7 bytes

say now


about now

# Japt, 1 byte

K


Try it online!

• Welcome to Japt! :) (and the site) If you weren't aware, there's an open bounty running for Japt solutions. – Shaggy Mar 21 '19 at 21:51

# Trigger, 14 bytes

ABAAA AAB    B


Try it online!

A                NOT the value of the A trigger, making it one
B               NOT B
AAA            Print "A"
AAB        Go to the nearest B in the program. If it is the same distance, it picks it randomly. This can go to the NOT B command or go to the next B command, running the print A or ending the program, respectively.


# Shellscript (as implemented by ttyrec), 0 bytes

OK, here's a version of this idea that uses an interpreter that can actually be programmed with.

The ttyrec command by default just passes everything it sees on standard input to a shell, and thus obeys our definition of a programming language (it's Turing-complete, because bash is; it's basically just an alternate front-end to bash, and so is basically a shellscript interpreter that can be used to program with). However, it also creates a file ttyrecord containing a recording of the shell's output, and that file starts with the current time, in binary (and is also affected in some ways by the system's CPU and swapping load, as it tries to separate the output into frames). Thus, it produces a file with nondeterministic content as output.

• I'm not using any commands. Shellscript is Turing-complete. At least one implementation of it produces nondeterministic output in addition to running the program given, thus you get the output you want even with no commands. Languages are defined by the interpreter here. – user62131 Nov 30 '16 at 20:56
• (the above was in reply to a since-deleted comment that this wasn't valid due to not using commands) – user62131 Nov 30 '16 at 21:03

## JavaScript, 8 bytes

Date.now


This evaluates to a function whose return value is nondeterministic, and conveniently doesn't actually need to be bound to anything specific to work.

• Basically, this is the same as the Date answer. – Ismael Miguel Nov 30 '16 at 23:20
• @IsmaelMiguel I did have the idea of returning a builtin first; I just returned the wrong builtin. – Neil Dec 1 '16 at 0:31

## Batch, 6 4 bytes

time


Needs to be run with <nul which is apparently permissible.