# 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

# PHP, 12 bytes

<?=uniqid();


Outputs a unique ID 583f4da627ee3 based on the current time in microseconds.

• <?=time(); <-- 10 bytes. – Ismael Miguel Nov 30 '16 at 23:23
• @IsmaelMiguel uniqid() is 1'000'000 times more undetermined than time() ;) – Mario Nov 30 '16 at 23:40
• I'm not saying the oposite. But proposing another answer. You're free to pick that one. – Ismael Miguel Nov 30 '16 at 23:45
• @IsmaelMiguel someone else gave the same answer already... – Mario Nov 30 '16 at 23:46

# Groovy, 9 bytes

{print{}}

Outputs:

• Aha, nice idea! The 7-byte $System is the shortest one I could find. – Greg Martin Dec 1 '16 at 9:25 # Jelly, 2 bytes 9X  Idk if this works. I've never done anything in jelly before, and I'm on my phone right now. Int from 0 to 9. • Prints 09 every time for me. 9X works though – ETHproductions Nov 30 '16 at 20:57 • @ETHproductions Thanks. That was my original answer, I edited because I thought it didn't work. :/ I can't test things on my phone, so I had to go with what looked right from never using the language before. – Pavel Nov 30 '16 at 21:28 • It's [1, 9], not [0, 9]. Also, you can do ⁹X to do [1, 256] for the same bytecount. – Erik the Outgolfer Dec 2 '16 at 21:29 # C#, 36 22 bytes a=()=>a.GetHashCode();  Yay. • Why the braces and the return? Just make it ()=>Environment.TickCount; – Dennis_E Dec 1 '16 at 15:18 • @Dennis_E Yeah I didn't know you could do it like that for one liners, thanks! – Yodle Dec 1 '16 at 15:37 • You beat the javas :[ Have an upvote. (verbose language users like us gotta stick together) – Poke Dec 1 '16 at 15:39 • @Poke :D I'm trying to figure out if there's an even shorter way, but so far most of the other things for the function don't return different things each run. Although doing a.Target returns nondeterministic+<>c__DisplayClass0_0 which has 0_0 in it, which is cool. – Yodle Dec 1 '16 at 15:41 • Wouldn't DateTime.Now also fit the requirements? It produces different output at different times and is shorter than Environment.TickCOunt() or a.GetHashCode(). – Snowfire Dec 2 '16 at 7:59 ## C++, 26 19 Bytes std::cout<<new int;  Returns a different memory address each time it's run • What does the * do? – Pavel Dec 2 '16 at 8:21 • @Pavel int* means a pointer to an integer. – mbomb007 Dec 2 '16 at 14:39 • Isn't this just a snippet? A program would need a main function... – univalence Mar 5 '17 at 12:56 # Minecraft, 2 bytes /r  Must be written into chat when playing on multiplayer servers. Will throw an error if you hadn't messaged (/tell) anybody recently. Otherwise, shows both players a random message. Note: I'm not really sure if this is a legit solution :) ### Minecraft, 4 bytes (+2 blocks) help  Ties with another Minecraft answer from @Pavel This is based on Minecraft's Easter egg: When you type help or /help in a Command block, a random message starting with "Searge says:" is displayed, for example "Searge says: Ask for help on twitter". Here is a full list of messages. • /r is not a Minecraft command. It only exists on servers which implement it, usually with Bukkit/Spigot/Paper plugins. – Redwolf Programs Oct 18 '20 at 16:20 # INTERCAL, 0 2 bytes (0+2 for command flag) Try it online! (I don't know if the TiO compiler reproduces this functionality correctly) This is not a valid INTERCAL program, so attempting to run it gives Error 778 - UNEXPLAINED COMPILER BUG. However, when INTERCAL is run without the -b command flag, there is a small chance that it doesn't run and throws Error 774 - RANDOM COMPILER BUG. So if errors count as output for this challenge, then INTERCAL might actually be good for something! # INTERCAL, 17 bytes DO %9 READ OUT #5  Try it online! This is a more standard approach. It has 9% chance of printing V before terminating (with an error, but it gives the output, so who cares?) • Compiler flags have to be included in the byte count. See meta post. – mbomb007 Oct 6 '17 at 16:59 • @mbomb007 It doesn't use any compiler flags--that's the whole point. The "RANDOM COMPILER BUG" occurs when a program is run without the -b flag. – KSmarts Oct 6 '17 at 18:22 • Any difference from the standard flags counts. So if removing the flag is the difference, that's a one-byte difference. – mbomb007 Oct 6 '17 at 19:08 • @mbomb007, although any sensible person would run the INTERCAL compiler with the -b option, a sensible person wouldn't be using INTERCAL in the first place. – Mark Oct 6 '17 at 22:07 # x86/amd64 machine language (Pentium or higher), 3 bytes 0: 0f 31 rdtsc 2: c3 retq  This uses the RDTSC instruction that may not be available on older processors. To test, try the following C program on Linux x86/amd64 #include <stdio.h> int main(){ for( int i = 0; i < 10; i++ ) { printf( "%d\n", ((int(*)())"\x0f\x31\xc3")() ); } }  • To clarify how the value is returned; RDTSC loads the most significant 32 bits into edx, and the least significant 32 bits into eax. The convention for returns in this matchine code is that an int-sized return value is stored in eax, so the function's return value is suitably nondeterministic. – user62131 Nov 30 '16 at 21:38 # Cubix, 3 bytes (non-competing) @OD  Outputs a random positive number of zeroes. Non-competing because I added D just a few minutes ago. Before it was added, there was absolutely no way to randomize anything in Cubix. Test it online! ### How it works Before the code is run, it's padded with no-ops . and formed into a cube net. Here's what the net for this particular program looks like:  @ O D . . .  Now the code is run, starting on the left-most face and heading to the right. First, O outputs the top item on the stack as a number. At the beginning of the program, the stack is an infinite fount of zeroes, so this prints 0. Next, D sends the IP (instruction pointer) in a random direction: possibly up to the @ which ends the program, and possibly back to the O which prints another 0. This continues until whenever the IP hits the @. @DO and OD@ also work, each printing zero or more zeroes. # Lua, 9 bytes print({})  Outputs the internal address of the Lua table object: table: 0x2370ab0  If you're running from the interactive interpreter, you can use just 3 bytes: > ={} table: 0x23719c0  # C, 19 f(a,b){putchar(b);}  In C the second declared variable in a function's arguments is random based on memory. Assuming the arguments were not actually declared, i.e. you just called f();. So this function can be simply called with no input-arguments. That is, just: f(); and the output will be a random character. Try it online! (Note: output might be an unprintable character, run the program a few times to see variation, you should get more printable characters than non-printable characters) # C (gcc), 18 bytes f(){printf("%d");}  This one may be difficult to test since TIO will give you a cache hit. Just add some whitespace and try it again. Try it online! ## Retina, 3 bytes ?&  Try it online! Yay, Retina can finally compete in challenges that require randomness! \o/ ### Explanation ?& is a compound stage which executes its child stage with a 50% probability. That child stage is itself a Count stage, which counts the number of empty matches in the empty input (1). So if the child stage is run, the result is 1, if it isn't, then the empty input remains unchanged and we get an empty string. A fun alternative for the same byte count would be: ?+  Try it online! This one uses a random loop (which uses a coin toss before each iteration to decide whether to continue). This one has a 50% chance of printing an empty string, 25% of printing 1 (one iteration) and a 25% chance of printing 2 (two or more iterations). # Lost, 7 bytes @%" ///  Try it online! Since Lost starts the pointer in a random place facing a random direction, it's refreshing not making the output deterministic for once. I think this is the optimal solution since you need the @ and % in order to end the program, the " to push stuff to the stack at random, and the /// to avoid infinite loops. • The challenge does not require the program to halt. Thus @% alone will work. This either loops forever outputting nothing or halts and outputs a newline. – Wheat Wizard Aug 23 '18 at 3:20 # Intercept 1.1, 37 bytes Prints newlines to the terminal. You'll probably have to leave this one overnight, as there is a delay of 5-15 minutes (it's random!) between each newline. Note that while you can determine what is being printed, you can't determine how often it's being printed. Input is marked with a >>. The command prompt is the empty >>. Assuming a system with only TZ_INFECT installed...  >> malware bm bitminer creating bm (bitminer) ... wait a minute ... finished creating bm (bitminer) >> software install 1 Success bm installed ...wait... (newlines) >>  Note that I'm using a custom client that prefixes [BROADCAST] to all broadcast events. # How??? TZ_INFECT is Intercept's malware generator. We can generate a bitminer by running malware <name> bitminer. This will create a new piece of software with the given name of type bitminer We then install the bitminer: software install <index>, where index is the 0-based index of the software as given by software list. This is why I made sure the only piece of software on the system was the malware generator. This places our new bitminer at index 1. There is a bug in the implementation of bitminer that results in an empty broadcast event to be sent to the client whenever bits are generated. Since bits are generated at random intervals, the broadcasts are sent at random intervals. Voilia, non-deterministic output! Note: the newlines are harder to detect using the official game client, but you can see them by running a command and watching the newlines slowly push the resulting output off the screen. Screenshots coming in a few hours while I wait for the output. After 20 minutes (the [BROADCAST] is a newline): After 2 days: # PHP, 10 Byte <?=time();  This prints the current Unix time which – of course – isn't random but changes when you call the program several times. The output I just got is 1480548602. • Welcome to PPCG! Nice answer, by the way. – Erik the Outgolfer Dec 2 '16 at 21:33 # APL, 2 bytes ?9  This uses APL's roll (?) operator. The program prints a pseudo-random number between 1 and 9. • Also works in J. – Conor O'Brien Dec 1 '16 at 11:27 • Looks deterministic to me, except if ⎕RL≡⍬2 or after executing ⎕RL←0. A safer bet is ⎕TS or ⎕AI. – Adám Dec 5 '16 at 23:43 • Update: Your code has now become non-deterministic, as the default has become to ask the OS for a random number. Try it online! – Adám Feb 2 '18 at 9:30 # Brachylog, 3 bytes 9$?


Try it online!

$? 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. # 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  ## PHP 10 bytes <?=rand();  Prints a random number between 0 and getrandmax(). Which may vary based on what computer it's run on. # Java2K, 9 bytes I don't recommend trying to write an approximation of a deterministic program in this language. 11 6/*/_\  This function has a 90% chance to return 1, otherwise it will return a random number. 11 6 is the name of the division function. A function is called like <name>/<arg0>/<arg1>\. Basicaly every function returns the "correct" result 90% of the time, or else a random number. The token * is replaced by a random number, say 203. The _ token is replaced by the previous argument, i.e. 203. So, this function will divide 203 by 203 which has (see below) a 90% chance of returning 1. # 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. # Ruby, 14 bytes p ?..object_id  Returns object id of the string '.' # TI-Basic, 2 bytes Very similar to this answer. The getTime token is two bytes and is located at EF 0A. getTime  • rand is 1 byte. – bb94 Mar 19 '19 at 0:18 • @bb94 "A pseudo-random number generator that always has the same seed does not count." – Timtech Apr 2 '19 at 0:34 # 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 } }  # 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  # Kotlin script (.kts), 12 bytes print(Any()) Any is a compile-time time wrapper for Object, default toString() of any object is class name@hashcode. Probably the shortest solution that runs on the JVM. If .kts is cheating: 18 bytes: fun a()="${Any()}" (forgot functions are a valid answer)

38 bytes: fun main(a:Array<String>)=print(Any())

• Trying this on my OpenJDK JRE with a freshly downloaded kotlinc 1.0.5-2 repeatably outputs java.lang.Object@5bc1903. Doesn't seem too nondeterministic? – Paŭlo Ebermann Dec 4 '16 at 19:31
• Hm, didn't think of that - is it still a valid answer if it's different on every machine? Default hashcode impl. uses the internal memory address of the object IIRC. – F. George Dec 5 '16 at 4:23
• Just out of curiosity, what does it output on your machine? – Paŭlo Ebermann Dec 5 '16 at 18:02
• java.lang.Object@21471ca8 but it seems to vary between IDE restarts and even how I name the source file. Makes sense, as the hashcode is literally just the memory address of the object. – F. George Dec 5 '16 at 20:29