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

1 2 3 4
5
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\$
0
\$\begingroup\$

Pyt, 1 byte

ɽ

Returns a random 32-bit integer.

Also 1 byte: ɹ, .

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

Gol><>, 3 bytes

x1h

The 'x' is a randomizer for the direction of the pointer, the 1 pushes a 1, and the h outputs and halts.

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ You can also do Sxh to print a random float between 0 and 1 \$\endgroup\$
    – Jo King
    Mar 1, 2019 at 2:31
  • \$\begingroup\$ @JoKing I didn't think of that, thanks for pointing that out. that works as well. Though I don't think there is a smaller version of this \$\endgroup\$ Mar 1, 2019 at 2:57
0
\$\begingroup\$

05AB1E, 2 bytes

Any program matching /^[ATт₁-₆]Ω|ž[a-g]$/ will give nondeterministic output. There are, of course, infinitely many programs that can do this, but these are all the two-byters. Unfortunately, I could not find a one-byter... :(

Try them online!

Explanation

The ones starting with ž are constants. The ones used here are time constants - ža, žb, žc, žd, že, žf, and žg are hours, minutes, seconds, microseconds, day, month, and year, respectively. The ones ending in Ω pick a random element (for lists), character (for strings), or digit (for integers) from top of stack. The one-byte commands that I could find that push something with more than one distinct element/character/digit were A, T, т, , , , , , and , which push abcdefghijklmnopqrstuvwxyz, 10, 100, 256, 26, 95, 1000, 255, and 36, respectively.

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

ThumbGolf, 4 bytes

Machine code:

de78 de20

Assembly:

        // Include ThumbGolf wrapper macros
        .include "thumbgolf.inc"
        .globl main
        .thumb_func
main:
        // Read random integer into r0
        rand    r0 // udf #0170
        // Print to stdout in base 10
        puti    r0 // udf #0040
        // Not required to exit, so just crash

Internally, ThumbGolf uses /dev/urandom, so this is guaranteed to be nondeterministic.

Alternative version, 2 bytes

Machine code:

de21

Assembly:

        // Include ThumbGolf wrapper macros
        .include "thumbgolf.inc"
        .globl main
        .thumb_func
main:
        // print address of argv
        // printf("%i", (int)argv)
        puti    r1 // udf #0041
        // exit by crash

Prints the memory address of argv which is almost guaranteed to be dynamically allocated, and therefore, nondeterministic.

However, it is context sensitive unlike the 4 byte solution.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Non-competing status shouldn't be used nowadays. Answers in languages newer than the question are allowed, obviously considering that you don't hardcode the answer to the challenge into the language's interpreter and submit a 0-byter (or similar). That is already a standard loophole. \$\endgroup\$
    – Makonede
    Feb 6, 2021 at 23:51
  • \$\begingroup\$ Also just realized; your two-byter is Þ! in Unicode. :P \$\endgroup\$
    – Makonede
    Mar 2, 2021 at 22:49
0
\$\begingroup\$

Phooey, TIO version, 4 bytes

<2$i

Try it online!

Abuses a bug to print the frame pointer.

This is because the tape does not wrap, so the tape just underflows to the stack.

<2 moves the pointer 16 bytes back, $i prints as an integer.

Very dependent on the version of the binary.

Phooey, proper version, 5 4 bytes

~t$i

Try it online!

~t stores the Unix time to the tape, and I already explained $i.

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

CSASM v2.2.1.2, 39 bytes

func main:
extern Random.Next
print
ret
end

CSASM has a built-in System.Random object that gets initialized to new System.Random() when CSASM.Core.Sandbox.Main(System.Reflection.MethodInfo, int, string[]) is called.

The default System.Random constructor initializes the seed to Environment.TickCount, which is different every time the executable runs.

extern Random.Next calls Random.Next() on the aforementioned object, which returns a positive int value.

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

Thunno, \$ 4 \log_{256}(96) \approx \$ 3 bytes

(actually 3.29 bytes but that doesn't show up on the leaderboard)

9RZw

Attempt This Online!

Outputs a random integer from 0 to 8:

  • 9R gets range(0, 9) (i.e. [0, 1, ..., 8])
  • Zw gets a random element of that list
\$\endgroup\$
2
  • \$\begingroup\$ This looks like 4 bytes to me. How do you get 3.29 bytes? You realize that coded in binary, it would have to be representable in whole bits at the very least. \$\endgroup\$
    – mbomb007
    Jan 10, 2023 at 20:37
  • 1
    \$\begingroup\$ There is a consensus that fractional byte counts are allowed. Since Thunno uses the 96 printable ASCII characters as its codepage, the character count of every Thunno program can be multiplied by 0.82 \$\endgroup\$
    – The Thonnu
    Jan 11, 2023 at 7:30
0
\$\begingroup\$

Thunno 2, 2 bytes

Attempt This Online!

Outputs a random integer from 1 to 9.

\$\endgroup\$
0
+100
\$\begingroup\$

Tamsin (Compiler), 16 bytes

main=any@'\xf0'.

Explanation

main=             # output
     any          #   read 1 utf-8 char
        @         #   from
         '\xf0'.  #   '\xf0'

The Tamsin compiler produces C code that omits out-of-bounds checks during the reading of UTF-8 characters. Consequently, upon encountering \xf0, it proceeds to read an additional three bytes beyond the string's limit which are also output.

The Tamsin interpreter (used by TIO) does not suffer from this issue (it simply throws an assertion error).

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

Pip, 1 byte

r

Attempt This Online!

Suggested by @DLosc

Equivalent to Python's random.random() or JS's Math.random().

\$\endgroup\$
1
  • \$\begingroup\$ r works too ;) \$\endgroup\$
    – DLosc
    Mar 8 at 18:25
1 2 3 4
5

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.