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

129 Answers 129

1
\$\begingroup\$

Ink, 5 bytes

{~a|}

Try it online!

Either outputs "a" or nothing.

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

Perl 6, 7 bytes

say now

about now

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

Japt, 1 byte

K

Try it online!

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

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

Pxem (Filename: 5 bytes; Contents: 0 byte)

  • Filename: x.r.n
  • File content is empty.

Explaination

  • x pushes an ascii code of the character (120) as a signed integer.
  • .r pops 120 to push back one of 0-119.
  • .n pops the integer to output as a decimal.
\$\endgroup\$
1
\$\begingroup\$

C (gcc), 63 54 bytes

main(){int a;for(char*b;a=3;b++)for(;a;a--)printf(b);}

Try it online!

I can't even remember how this one works.

Down to 54 bytes by 2x-1.

Puts instead of printf creates triangle patterns instead, but I think they're boring.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 54 bytes \$\endgroup\$
    – user100947
    Feb 26, 2021 at 10:02
1
\$\begingroup\$

EmojiCoder, 44 bytes

🙈🔢🌚🌝🌚🌚🌚🌚🌚🌝
✋

Try it online!

Push some random integer between 0 to 65 (chosen randomly) and output top of stack.

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

Barrel, 2 bytes

|n

Gets a random integer with | and prints it as a number with n.

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

.mmo (MMIX executable), 128 120 bytes

(xxd --jelly)

00000000: 98090100 98010001 00000100 e3ff0130  Ƭµ¢¡Ƭ¢¡¢¡¡¢¡ẉ”¢0
00000010: 00000103 e3ff0140 00000303 e3ff0140  ¡¡¢¤ẉ”¢@¡¡¤¤ẉ”¢@
00000020: e0012000 87000100 ef00a0a0 eb004040  ṭ¢ ¡⁷¡¢¡ṁ¡ɦɦḟ¡@@
00000030: a7000100 00000601 98020008 00000150  ʂ¡¢¡¡¡©¢Ƭ£¡®¡¡¢P
00000040: 00000000 00000002 20000000 98020008  ¡¡¡¡¡¡¡£ ¡¡¡Ƭ£¡®
00000050: 00000002 2f646576 2f72616e 646f6d00  ¡¡¡£/dev/random¡
00000060: 980a00ff 00000000 00000100 980b0000  Ƭ½¡”¡¡¡¡¡¡¢¡Ƭ¿¡¡
00000070: 00000000 980c0001                    ¡¡¡¡Ƭ€¡¢

Outputs two random characters in range @-_ to stdout.

Explanation

98090100 lop_pre 1,0                    (preamble, mmo v1, 0 tetras)
98010001 lop_loc 0,1                    (next tetra says where to load)
00000100 (256)
E3FF0130  SETL  $255,random
00000103  TRAP  0,Fopen,3               (open fd 3 for bin read from /dev/random)
E3FF0140  SETL  $255,data
00000303  TRAP  0,Fread,3               (read two bytes of data)
E3FF0140  SETL  $255,data               (set up $255 for writing it back out)
E0012000  SETH  $1,#2000                (we know where the data is)
87000100  LDWU  $0,$1,0                 (read those bytes from memory)
EF00A0A0  ANDNL $0,#A0A0                (ensure C0 control or @-_)
EB004040  ORL   $0,#4040                (ensure @-_)
A7000100  STWU  $0,$1,0                 (write them back to memory)
00000601  TRAP  0,Fwrite,StdOut         (write two bytes out)
98020008 lop_skip 8                     (encodes the next two tetras)
          TRAP  0,Halt,0                (halt)
         random OCTA fname              (argument 1 of fopen: ptr to filename)
00000150  (cont)
00000000  OCTA BinaryRead               (argument 2: mode)
00000002  (cont)
20000000 data OCTA Data_Segment         (argument 1 of fread/fwrite: buffer addr)
98020008 lop_skip 8                     (encodes cont + start of next)
          OCTA 2                        (argument 2: amount)
00000002  (cont)
2F646576 fname BYTE "/dev"
2F72616E  BYTE "/ran"
646F6D00  BYTE "dom\0"
980A00FF lop_post 255                   (one global register)
00000000
00000100                                (start at 0x100)
980B0000 lop_stab                       (symbol table)
00000000                                (no symbols)
980C0001 lop_end 1                      (one symtab tetra)

Basically, this reads two characters from /dev/random, then, after a bit of munging to ensure they're printable, dumps them to stdout.

I also used lop_skip to cut two tetras from the code.

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

SNOBOL4 (CSNOBOL4), 19 bytes

 output =date()
end

Are there any other ways to obtain a random value in this language?

Try it online!

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

APOL, 1 byte

This is just the random float instruction, the result of which is implicitly printed.

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

Knight, 3 bytes

O R

Try it online!

Not a complicated answer.

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

SNOBOL4 (CSNOBOL4), 15 14 bytes

I got a hint from user62131's sh + procps answer.

 exit('w')
end

Try it online!

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

Vyxal, 2 bytes

9℅

Try it online!

Outputs a random integer from 0 to 9.

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

Fortran (GFortran), 12 bytes

print*,i
end

Try it online! Fortran has a bunch of "random" functions, ironically all deterministic, like RAND, needing all kinds of complicated seeds to make a mathematically pure random distribution. But in this code I just grab an uninitialized integer i, and print whatever is in that memory location.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – user62131
    Nov 30, 2016 at 20:56
  • \$\begingroup\$ (the above was in reply to a since-deleted comment that this wasn't valid due to not using commands) \$\endgroup\$
    – user62131
    Nov 30, 2016 at 21:03
0
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Basically, this is the same as the Date answer. \$\endgroup\$ Nov 30, 2016 at 23:20
  • \$\begingroup\$ @IsmaelMiguel I did have the idea of returning a builtin first; I just returned the wrong builtin. \$\endgroup\$
    – Neil
    Dec 1, 2016 at 0:31
0
\$\begingroup\$

Batch, 6 4 bytes

time

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

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

Swift 3, 13 bytes

print(Date())
\$\endgroup\$
0
\$\begingroup\$

QBIC, 4 bytes

?_r|

This generates and prints a random number between 0 and 10. QBIC uses the classical RANDOMIZE TIMER at the start of execution to set the RNG.

\$\endgroup\$
0
\$\begingroup\$

Actually, 1 byte

G

Try it online!

Good old rand(). In Python 3, 2500 random bits from the system's cryptographically-secure randomness source (getrandom() for Linux, /dev/urandom for *NIX, or CryptGenRandom for Windows) are used for the seed, falling back on the current UNIX time (as precisely as possible for the given platform - at minimum, 1-second precision) if such a source of randomness is not available.

\$\endgroup\$
0
\$\begingroup\$

Microscript, 2 bytes

r9

Produces a random integer on [0,8]

\$\endgroup\$
0
\$\begingroup\$

Mouse2002, 7 bytes

&RAND !
\$\endgroup\$
0
\$\begingroup\$

Microscript II, 1 byte

R

Produces a random 64-bit float on [0,1).

Another one-byte solution would be C, which produces a new continuation object, whose timestamp (which the reference implementation includes in its string representation) will be nondeterministic.

\$\endgroup\$
0
\$\begingroup\$

HSPAL, 18 bytes

26FFFF
400000
120000

Prints a random 16-bit integer.

\$\endgroup\$
0
\$\begingroup\$

Math++, 5 bytes

$rand

Produces a random 64-bit float

\$\endgroup\$
0
\$\begingroup\$

ASP VBScript, 43 bytes

<%=createobject("scriptlet.typelib").guid%>

Outputs a unique ID like {52076580-3151-4EE7-AAFD-D975CD141EE4} based on current date/time.

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

C, 22 bytes

f(){putchar(time(0));}
\$\endgroup\$
2
  • \$\begingroup\$ OP indicates in the comments that a full program is not needed and a function will suffice. Might I suggest replacing main with f to save 3 bytes? \$\endgroup\$ Apr 11, 2017 at 19:48
  • \$\begingroup\$ yes i replace main with f... thank you and a good day \$\endgroup\$
    – user58988
    Apr 12, 2017 at 5:18
0
\$\begingroup\$

Chip-8, 4 bytes

0xCFFF 'RND vF,FF
0xFF18 'LD ST,vF

This plays a sound for between 0 and 4.25 seconds. The seed always starts at 0, but it updates during the display interrupt which has a tiny chance of happening before the randomizer call, I hope.

\$\endgroup\$

Your Answer

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

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