104
\$\begingroup\$

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.

Leaderboard

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>

\$\endgroup\$
27
  • 41
    \$\begingroup\$ @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. \$\endgroup\$ Nov 30, 2016 at 20:44
  • 13
    \$\begingroup\$ @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) \$\endgroup\$ Nov 30, 2016 at 21:00
  • 8
    \$\begingroup\$ 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. \$\endgroup\$
    – user62131
    Nov 30, 2016 at 21:23
  • 5
    \$\begingroup\$ 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. \$\endgroup\$
    – WGroleau
    Dec 1, 2016 at 3:30
  • 4
    \$\begingroup\$ @MartinEnder damn, missed my free GCC pizza yesterday. \$\endgroup\$ Dec 2, 2016 at 12:04

134 Answers 134

3
\$\begingroup\$

JavaScript (full program), 12 bytes

throw is much smaller than console.log() or process.stdout.write(), it does halt execution, but that's not an issue.

throw Date()
\$\endgroup\$
1
  • \$\begingroup\$ eval(Date()) another fun 12 byter, but idk if its valid :P \$\endgroup\$ Aug 17, 2022 at 13:11
2
\$\begingroup\$

Brachylog, 3 bytes

9$?

Try it online!

Explanation

$? is the random number predicate. When given an integer as input (here, 9), its output will be unified with an integer between 0 and 9 uniformely at random.

\$\endgroup\$
2
\$\begingroup\$

Randwork, 11 bytes

Uses the Randwork+ instruction set, because that's the only specification with an existing interpreter.

Do anything

This statement executes a random instruction from the instruction set. There is a 7/28 (25%) chance of non-empty output. I calculated the probability by viewing the source code of the interpreter. The instructions that can produce output are:

Write the ASCII equivalence of a random byte
Beep
Write the ASCII equivalence of byte 1
Write the ASCII equivalence of byte 2
Write the ASCII equivalence of byte 3
Write the ASCII equivalence of byte 4
Display the Hello World message

Bytes 1-4 have not been set, so output of any of them will be a NUL byte. The 7 possibilities of non-empty output are (in corresponding order):

\x?? - a random byte
\x07 - the bell character (beep)
\x00 - NUL
\x00
\x00
\x00
Hello world
\$\endgroup\$
2
\$\begingroup\$

TI-83 Hex Assembly, 4 bytes

PROGRAM:ND
:AsmPrgm
:EF0A45
:C9

Run it with Asm(PrgmND). Calls the _PutS system library call (0x450a), but because it doesn't set HL it will print whatever HL pointed to last, usually a lot of garbage text.

I count this as 4 bytes, because each pair of hex digits is one byte.

\$\endgroup\$
2
\$\begingroup\$

Ruby, 14 bytes

p ?..object_id

Returns object id of the string '.'

\$\endgroup\$
2
\$\begingroup\$

TI-Basic, 2 bytes

Very similar to this answer. The getTime token is two bytes and is located at EF 0A.

getTime
\$\endgroup\$
2
  • \$\begingroup\$ rand is 1 byte. \$\endgroup\$
    – bb94
    Mar 19, 2019 at 0:18
  • 1
    \$\begingroup\$ @bb94 "A pseudo-random number generator that always has the same seed does not count." \$\endgroup\$
    – Timtech
    Apr 2, 2019 at 0:34
2
\$\begingroup\$

C#, 72 bytes

It's alot longer than the other C# answer but hey, different approach and fully functioning console application. Why not?

Golfed

using System;class P{static void Main(){Console.Write(Guid.NewGuid());}}

Ungolfed

using System;
class P
{
    static void Main()
    {
        Console.Write(Guid.NewGuid()); //Create a new random GUID and print it
    } 
}
\$\endgroup\$
2
\$\begingroup\$

BrainFlump, 5 bytes

:+:;.

Try it online!

Outputs either a NUL or SOH character

Explanation

BrainFlump is the latest iteration of BrainFl* languages having different memory models (BrainFlak is a stack, BrainFlueue is a queue, etc)

In BrainFlump, memory consists of a Cell and a Dump.

The Cell is a single numerical value, and the Dump is an unordered collection of numerical values.

When the program starts, the Dump is empty, and the Cell is 0.

:      Push the Cell's value to the Dump
 +     Increment the Cell
  :    Push the Cell's value to the Dump
   ;   Pop a value from the Dump (randomly) to the Cell
    .  Print the Cell's value as an ASCII character
       The Cell's value will either be 0 or 1, and as it's printed as an
       ASCII character, this results in NUL or SOH
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Keg, 1 byte

~

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

\$\endgroup\$
2
  • \$\begingroup\$ Polyglots with Volatile \$\endgroup\$
    – lyxal
    Oct 25, 2019 at 22:21
  • \$\begingroup\$ Volatile doesn't have implicit output. \$\endgroup\$
    – user85052
    Oct 25, 2019 at 22:49
2
\$\begingroup\$

Braingolf, 2 bytes

2r

Pushes 2 to the stack, then pushes a random number between 0 and the last item on the stack (2), ie randomly selects either 0 or 1. Implicitly prints the last item on the stack (the random number)

\$\endgroup\$
2
\$\begingroup\$

><> (Fish), 4 bytes

1n0x

Try it

Prints 1, then prints 0 or 1 randomly, as the x will cause the instruction pointer to move either left or right.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 3 bytes. Prints 1 a random number of times. This might not be right, never used ><> before. \$\endgroup\$
    – noodle man
    Jun 4, 2023 at 3:46
  • \$\begingroup\$ @noodleman Note that your code smells fishy when run. \$\endgroup\$ Oct 14, 2023 at 9:27
2
\$\begingroup\$

Uiua, 1 byte

Try it!

Prints a random float from 0 to 1 each time the program is run.

\$\endgroup\$
1
  • \$\begingroup\$ I like the language's glyphs. Very nice! It's also really cool how you can hover over a glyph for more information. \$\endgroup\$
    – mbomb007
    Oct 13, 2023 at 16:03
2
\$\begingroup\$

C (gcc), 24 bytes

main(){printf("%s",.0);}

My favourite, since the warning messages in stderr also get corrupted slightly.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Python, 11 bytes

1/(id(2)%3)

Attempt This Online!

Sometimes it outputs nothing, sometimes it outputs a ZeroDivisionError message.

Matches @Blue's print id(1), but that needs parentheses in Python 3, making it 12 bytes there.

\$\endgroup\$
1
\$\begingroup\$

Wirefunge - 2 bytes

¿>

¿ - Randomized output every iteration

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

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 13 bytes

put Bool.pick
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Thue, 17 bytes

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

Randomly prints either nothing, or the digit 1.

\$\endgroup\$
1
\$\begingroup\$

T-SQL 15 bytes

print getdate()
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

Shell, 2 bytes

ps

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

\$\endgroup\$
1
\$\begingroup\$

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])

\$\endgroup\$
1
\$\begingroup\$

SmileBASIC, 6 bytes

?TIME$

Prints the current time.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.
\$\endgroup\$
1
\$\begingroup\$

Fourier, 3 bytes

9ro

Outputs a random number from 0 to 9.

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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