90
\$\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
  • 38
    \$\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\$ – Martin Ender Nov 30 '16 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\$ – Nathan Merrill Nov 30 '16 at 21:00
  • 2
    \$\begingroup\$ @MartinEnder Yeah, I agree with Nathan. \$\endgroup\$ – mbomb007 Nov 30 '16 at 21:01
  • 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 '16 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 '16 at 3:30

116 Answers 116

113
\$\begingroup\$

WinDbg, 1 byte

#

Wow! Never expected a 1 byte solution from WinDbg!

# searches for a disassembly pattern, but since there's no parameters, it looks to just return the next assembly instruction in whatever dump/process you're attached to. Not sure the logic for setting the initial address, but it does.

Sample output:

0:000> #
Search address set to 75959556 
user32!NtUserGetMessage+0xc
75959556 c21000          ret     10h

0:000> #
user32!NtUserGetMessage+0xf 
75959559 90              nop

0:000> #
user32!NtUserMessageCall 
7595955a 90              nop

0:000> #
user32!NtUserMessageCall+0x1 
7595955b 90              nop

0:000> #
user32!NtUserMessageCall+0x2 
7595955c 90              nop

0:000> #
user32!NtUserMessageCall+0x3 
7595955d 90              nop

0:000> #
user32!GetMessageW
7595955e 8bff            mov     edi,edi

0:000> #
user32!GetMessageW+0x2 
75959560 55              push    ebp

0:000> #
user32!GetMessageW+0x3 
75959561 8bec            mov     ebp,esp

0:000> #
user32!GetMessageW+0x5 
75959563 8b5510          mov     edx,dword ptr [ebp+10h]
\$\endgroup\$
2
  • 9
    \$\begingroup\$ One of the cooler answers here, this should win over a "Current Date" solution in my opinion. \$\endgroup\$ – Magic Octopus Urn Nov 30 '16 at 21:39
  • \$\begingroup\$ that above it seems the disassebly, step by step of the begin of some function in 386 intel cpu assembly \$\endgroup\$ – user58988 Dec 2 '16 at 22:05
63
\$\begingroup\$

Java 7, 33 30 27 bytes

int a(){return hashCode();}

Because Java.

\$\endgroup\$
17
  • 52
    \$\begingroup\$ Because Java. Probably the best explanation of Java ever. \$\endgroup\$ – F. George Nov 30 '16 at 21:35
  • 5
    \$\begingroup\$ @carusocomputing I had toString in a previous version but then the return type is String which is longer than int. Save the bytes! :] \$\endgroup\$ – Poke Nov 30 '16 at 22:17
  • 12
    \$\begingroup\$ Is this valid as a function? hashCode() is an abbreviation here for this.hashCode(), so it'd only work as an instance method, not a static method. In that case, you'd need additional code to create an object in the caller. That's relevant here because it's the code to create an object that's responsible for the nondeterminism. \$\endgroup\$ – user62131 Dec 1 '16 at 1:08
  • 16
    \$\begingroup\$ In Java 8: ()->hashCode() for 14 bytes. Just sayin' ;) \$\endgroup\$ – Olivier Grégoire Dec 1 '16 at 16:58
  • 4
    \$\begingroup\$ @pts I'm going based off of the meta post discussing the default submit structure for posts. Functions are allowed by default unless the challenge specifies that a full program is required. \$\endgroup\$ – Poke Dec 2 '16 at 18:36
59
\$\begingroup\$

MATLAB, 3 bytes

why

why provides answers to almost any question. A few examples:

why
The programmer suggested it.

why
To fool the tall good and smart system manager. 

why
You insisted on it.

why
How should I know?

This is shorter than any rand function I can think of.

\$\endgroup\$
2
  • 40
    \$\begingroup\$ MATLAB has a builtin for this? Why? \$\endgroup\$ – ETHproductions Dec 3 '16 at 20:46
  • 72
    \$\begingroup\$ @ETHproductions The programmer suggested it \$\endgroup\$ – Eddie Curtis Dec 5 '16 at 16:04
42
\$\begingroup\$

R, 1 byte

t

Outputs the function's source code and a memory pointer address which changes with every (re-)start of R.

\$\endgroup\$
41
\$\begingroup\$

huh?, 0 bytes


An empty program still produces output. The last lines of the Python interpreter that are executed:

print "..."
f = open('Notes.txt', 'w')
f.write(time.strftime("%c") + " - The user tried to give me commands again. I still have no idea what they are talking about...\n")

At the end of a program, the Python interpreter will print ..., then it will create/open a text file called Notes.txt and write a string which contains the current time in front.

\$\endgroup\$
3
  • 5
    \$\begingroup\$ Of all the things I thought people would use on my GitHub, I didn't think a joke language interpreter would be one :P \$\endgroup\$ – Kade Dec 2 '16 at 18:41
  • \$\begingroup\$ @Kade I was actually going to use it to answer another question as well (shortest code to play a sound, with only a single byte) -- but the question is now closed. \$\endgroup\$ – mbomb007 Dec 2 '16 at 19:36
  • \$\begingroup\$ Though it'd be non-competing unless I looked at the original .NET interpreter, I guess. \$\endgroup\$ – mbomb007 Dec 2 '16 at 19:43
31
\$\begingroup\$

Labyrinth, 5 bytes

v
!
@

Either prints 0 or nothing (50% chance each).

Try it online!

There is a very specific case in which Labyrinth exhibits random behaviour:

  • There must be a wall in front of the instruction pointer and behind it.
  • There must be a non-wall left and right of the instruction pointer.
  • The current top of the stack must be zero.

If all of those conditions are met, the direction the IP moves in is chosen (uniformly) randomly. The cherry on top is that those three conditions are impossible to meet in regular control flow, which means unless you modify the source code at runtime.

(This may seem a bit arbitrary, but it's actually the most consistent behaviour I could find for these conditions, since normally the direction of the IP always depends on the previous direction, its neighbours, and the sign of the top of the stack, and this seemed like an elegant way to include a source of randomness in the language.)

With the help of the source code rotation instructions (<^>v) it's possible to bring the IP into this situation. One such example is seen at the top. The IP initially points east and starts at the top. The v rotates the current column so that we get:

@
v
!

The IP moves along with this rotation so that it's still on the v, pointing east. All the conditions are fulfilled now, so the IP will either go up or down randomly. If it goes up, the program terminates immediately. If it goes down, it prints a zero, rotates the column again, and then terminates.

There are three other programs making use of this (one which also prints 0, one which prints 00 and one which prints 000):

v
@
!

"
>@!

"
>!@

(Actually there are a lot more than three other programs, because you could also use . instead of ! to print null bytes, or replace that " with a large variety of commands, but I believe they all work essentially the same.)

\$\endgroup\$
31
\$\begingroup\$

Minecraft, 5 4 bytes

op 8

Used by typing into a server's console or a command block and giving it power. Can be run from the chat interface by prepending a /.

Usually this does nothing, but if there's a player with the username "8" on the server, they will be given operator permissions. Note that while Minecraft normally requires usernames to be 3 characters long, some accounts with shorter name lengths were created before this restriction.

The version that can be demonstrated to be non-deterministic without one of these usernames or risk of giving a user operator permissions is here:

me @r

Displays a message to everyone, the message being the username of a random player. The op command only takes a string literal, not any script that returns a string.

The me command wouldn't really work for the first example, it would display "<your-username> 8". When run from a command block, it wouldn't be deterministic since all command blocks have the same "username" but running it from the chat interface would require the / for one extra byte.

\$\endgroup\$
11
  • \$\begingroup\$ So / is not included in the byte count? \$\endgroup\$ – Esolanging Fruit Dec 1 '16 at 5:36
  • 11
    \$\begingroup\$ @Challenger5 The slash is optional in command blocks, not allowed in the server console, and mandatory in the chat interface. \$\endgroup\$ – Pavel Dec 1 '16 at 5:47
  • 2
    \$\begingroup\$ Actually, it should be 4 bytes + 2 blocks (Command block and redstone source), or 6 blytes \$\endgroup\$ – RudolfJelin Dec 2 '16 at 16:38
  • 3
    \$\begingroup\$ @RudolphJelinek You can run it from the console without command blocks. \$\endgroup\$ – Pavel Dec 2 '16 at 17:10
  • 1
    \$\begingroup\$ Another non-deterministic option would be help in a command block, which is 4 bytes (and doesn't require pirated games). \$\endgroup\$ – Pokechu22 Dec 6 '16 at 19:03
29
\$\begingroup\$

Befunge (-93 and -98), 3 bytes

?.@

The ? sends execution in a random direction. If it goes up or down, it loops back to the ? and rerolls. If it goes left, the program wraps round to the @ and thus exits without printing anything. If it goes right, it prints 0 (the output produced by . when the stack is empty) and then exits on the @.

\$\endgroup\$
5
  • \$\begingroup\$ This isn't guaranteed to terminate, but I was going to post this exactly so +1 \$\endgroup\$ – Daniel Dec 1 '16 at 3:59
  • \$\begingroup\$ You may want to change the comma to a period to output 0 as a number instead of a null character (ASCII value 0). +1 \$\endgroup\$ – MercyBeaucou Dec 1 '16 at 4:19
  • \$\begingroup\$ It was . in the program I was using for testing, but somehow became a , when I copied it onto PPCG. Fixed. \$\endgroup\$ – user62131 Dec 1 '16 at 5:04
  • 7
    \$\begingroup\$ @Dopapp it terminates almost surely though, with probability 1. I'd take that as a guarantee ;) \$\endgroup\$ – Oliphaunt - reinstate Monica Dec 1 '16 at 9:17
  • \$\begingroup\$ @JamesHolderness I think you can do it in 1. Not sure if this counts though... \$\endgroup\$ – MercyBeaucou Dec 6 '16 at 18:18
23
\$\begingroup\$

Inform 7, 6 bytes

x is y

This isn't a valid Inform 7 program, since neither "x" nor "y" has been defined. So this throws an error.

However, some of Inform 7's error messages—including this one—are randomized. So the text it prints is technically non-deterministic.

A few possible outputs include:

Problem. The sentence 'x is y' appears to say two things are the same - I am reading 'x' and 'y' as two different things, and therefore it makes no sense to say that one is the other: it would be like saying that 'Adams is Jefferson'. It would be all right if the second thing were the name of a kind, perhaps with properties: for instance 'Virginia is a lighted room' says that something called Virginia exists and that it is a 'room', which is a kind I know about, combined with a property called 'lighted' which I also know about.

Problem. The sentence 'x is y' appears to say two things are the same - I am reading 'x' and 'y' as two different things, and therefore it makes no sense to say that one is the other: it would be like saying that 'Adam is Eve'. It would be all right if the second thing were the name of a kind, perhaps with properties: for instance 'Land of Nod is a lighted room' says that something called Land of Nod exists and that it is a 'room', which is a kind I know about, combined with a property called 'lighted' which I also know about.

Problem. The sentence 'x is y' appears to say two things are the same - I am reading 'x' and 'y' as two different things, and therefore it makes no sense to say that one is the other: it would be like saying that 'Clark Kent is Lex Luthor'. It would be all right if the second thing were the name of a kind, perhaps with properties: for instance 'Metropolis is a lighted room' says that something called Metropolis exists and that it is a 'room', which is a kind I know about, combined with a property called 'lighted' which I also know about.

Problem. The sentence 'x is y' appears to say two things are the same - I am reading 'x' and 'y' as two different things, and therefore it makes no sense to say that one is the other: it would be like saying that 'Aeschylus is Euripides'. It would be all right if the second thing were the name of a kind, perhaps with properties: for instance 'Underworld is a lighted room' says that something called Underworld exists and that it is a 'room', which is a kind I know about, combined with a property called 'lighted' which I also know about.

\$\endgroup\$
1
  • 7
    \$\begingroup\$ Even the error messages are verbose! \$\endgroup\$ – Destructible Lemon Dec 1 '16 at 22:15
22
\$\begingroup\$

sh + procps, 1 byte

w

This is the shortest solution I'm aware of that works via calling into external executables. procps is the responsible package for reporting information about the current system state (ps and friends), and is installed on most Linux distributions by default; w is the shortest-named command in it, and returns information about the logged-in users, but also some nondeterministic information like uptime.

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

JavaScript, 4 bytes

Date

A function which returns the current date/time. I think this is the shortest it will get...

Explanation

Since this seems to be causing a lot of confusion as to why it's valid, I'll try to explain.

In JavaScript, a function entry is valid if it can be assigned to a variable and called like a function. For example, this function is a valid entry:

function(){return Date()}

Because it is a function that can be assigned to a variable like so:

f=function(){return Date()}

And then run with f() as many times as necessary. Each time, it returns the current date/time string, which has been ruled non-deterministic by the OP.

This ES6 arrow function is also valid:

_=>Date()

It can be assigned with f=_=>Date(), then run with f() like the other one.

Now, here's another valid entry:

Date

Why? Because just like the other two entries, it can be assigned with f=Date and then called with f(), returning exactly the same thing as the other two. Try it:

var f = Date
<button onclick="console.log(f())">Run</button>

\$\endgroup\$
14
  • 5
    \$\begingroup\$ @milk Date is a function which, when called with no inputs, produces the current date/time. _=>Date() is a clearly valid entry which does exactly the same thing, so Date is a valid entry. \$\endgroup\$ – ETHproductions Nov 30 '16 at 21:06
  • 2
    \$\begingroup\$ Typing Date to the JavaScript console of my browser produces deterministic output, it always produces this: function Date() { [native code] }. You probably mean Date(), 6 bytes. \$\endgroup\$ – pts Dec 2 '16 at 17:51
  • 2
    \$\begingroup\$ @pts That would be a snippet, not a function or even a full program. This is a function entry, i.e. you call the function to run it. It's exactly the same as _=>Date(). \$\endgroup\$ – ETHproductions Dec 2 '16 at 17:52
  • 2
    \$\begingroup\$ if "date" above is ok than "malloc(8)" or "time(0)" would be ok in C too \$\endgroup\$ – user58988 Dec 2 '16 at 21:45
  • 3
    \$\begingroup\$ @RosLuP Date in JavaScript returns a function, just like n=>n. I don't believe malloc(8) returns a function, so it's either a full program or a snippet. \$\endgroup\$ – ETHproductions Dec 2 '16 at 22:01
14
\$\begingroup\$

Pyth, 2 bytes

O0

Explanation:

 0 0
O  Random float in [0, 1)

It's that, when O has 0 as its argument, it simply returns a random float between 0 and 1, exclusive.

Let's do it just for the heck of it!

Also, it seems that this can be sorta retro (thanks to 34718/mbomb007):

Dilbert: September 8, 1992


Pyth, 2 bytes

OT

Explanation:

 T 10
O  Random integer in [0, 10]

Try this boooooooooooooooring version instead >:(

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

Haskell, 49 bytes

import Unsafe.Coerce
main=putStr[unsafeCoerce(+)]

Unfortunately this seems to always outputs the same thing on TIO (I don't quite know why, but I have some guesses), so if you want to try it you should run it locally.

I've only tested this on Linux and OSX. I make no guarentees about Windows. If you are having trouble getting it to work on Linux I would be interested to know.

Explanation

What is unsafeCoerce?

This answer relies on unsafeCoerce. This function is a bit of magic, so first we are going to have to do a quick intro to Haskell's type system.

Haskell has something called type erasure. This means that the compiler checks all the types to make sure that nothing in the program is called on the wrong type. Once it is done with that there is no need to actually store type information any more, so Haskell erases it. So at runtime all data is the same and just relies on the fact that we already checked all the types before hand so nothing goes horribly wrong.

unsafeCoerce is a function that lies to the type checker. It tells it that it can take any input and produce any output; it's type is

forall a. forall b. a -> b

But it does nothing, it gives back the input exactly as it got it. So if you take a string like "abcd" and coerce it to an int using unsafeCoerce the result will be whatever the representation of "abcd" in memory is when interpreted as an integer.

How are functions represented in memory?

In Haskell, all complex objects including functions are internally represented as a pointer. This is a number in binary that "points" to a specific location in memory. This is because we want to pass these values by reference, since copying the whole thing is expensive, and since Haskell disallows mutation we can with no problem.

However simple objects like ints are passed by value since they are so small that copying them is about as expensive as copying a pointer would be. So they are not represented as pointers but rather just whatever structure they are.

So if we use unsafeCoerce from a complex object, say a function, to a simple object, say an Int, what happens is that the pointer to the function gets converted to the simple object. And the value of that simple object is dependent only on where the complex object is located not anything about what it is.

Address Space Layout Randomization

More reading

Many software vulnerabilities rely in part on being able to find particular functions in computer memory to access them. For these techniques you create some malicious code somewhere in memory (this can be done a few ways) and then by hijacking the stack pointer convince a program to run your code. In order to combat these exploits many systems implement something called Address Space Layout Randomization or ASLR. With ASLR key components are placed randomly so that their locations cannot be predicted. This means even if you do get control of the stack pointer it is hard to find where your malicious code is placed. ALSR is not the only technique used against these attacks but it is one we care about.

For Linux systems you can check of ASLR is on using

cat /proc/sys/kernel/randomize_va_space

Or since this is :

sysctl -anr "e_v"

There are three levels of security here 0 for off, and 1 and 2 for varying levels of on. My computer has this set to 2 (and your computer probably does too).

You can also set this. However do not do this unless you know what you are doing. Please do not mess with your kernel (unless you know what you are doing). For this reason I'm not going to include the command to do this, but you can look it up online or figure it out from the commands I already gave.

What this means for us is that the locations for objects allocated by Haskell at runtime is random or at least non-deterministic. This means that when we take a complex object like a function and convert it to a simple object like an Int the value of that object is random too.

The program

So that's what our program does. We coerce a function, (+) because it is short. We wrap this in a list and print it using putStr. Since putStr expects a string the compiler infers that the output of unsafeCoerce(+) must be a Char, which is a simple type.

So we end up printing a random one character string.

A more normal solution, 44 bytes

import System.Random
main=randomIO>>=putChar

Try it online!

For completion sake this is the "normal" Haskell approach. It is slightly shorter but far more boring.

\$\endgroup\$
12
\$\begingroup\$

Python 2, 11 bytes

print id(1)
\$\endgroup\$
2
  • 1
    \$\begingroup\$ That's the one I found. I had id(0), though. :) \$\endgroup\$ – mbomb007 Nov 30 '16 at 20:32
  • 2
    \$\begingroup\$ I beat you, technically, since I'm the OP and found it before I posted the question. I didn't want to post the question and immediately post my shortest answer. \$\endgroup\$ – mbomb007 Nov 30 '16 at 20:33
12
\$\begingroup\$

Bash (procps-ng), 2 bytes

ps

$$ is also a solution.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ If so, w is shorter and also comes from procps. \$\endgroup\$ – liori Dec 1 '16 at 2:48
  • 1
    \$\begingroup\$ You edited this into a duplicate of my answer. \$\endgroup\$ – user62131 Dec 1 '16 at 11:30
  • \$\begingroup\$ @ais523 oops, sorry. \$\endgroup\$ – Rɪᴋᴇʀ Dec 1 '16 at 14:57
  • \$\begingroup\$ Nice, my attempt was gzip. \$\endgroup\$ – Makonede Apr 15 at 22:07
11
\$\begingroup\$

PowerShell, 4 2 bytes

(crossed out 4 still looks like 4)

ps

This is the alias for Get-Process which will output the current process listing as a table, including handles, private memory, CPU time, etc.

Execute it via something like the following:

C:\Tools\Scripts\golfing>powershell.exe "ps"
\$\endgroup\$
5
  • 1
    \$\begingroup\$ I have to admit, I checked to see if it was actually crossed out. You really can't even tell. \$\endgroup\$ – Carcigenicate Dec 1 '16 at 0:25
  • \$\begingroup\$ @Carcigenicate I can tell if it is crossed without selecting the text (Ubuntu 16.04.1, Chrome 54.0.2840.100). \$\endgroup\$ – Erik the Outgolfer Dec 1 '16 at 19:38
  • \$\begingroup\$ Visible on android as well, though not clearly :p \$\endgroup\$ – tomsmeding Dec 1 '16 at 23:03
  • \$\begingroup\$ It looks fine in the iOS app. \$\endgroup\$ – Mateusz Piotrowski Dec 6 '16 at 12:43
  • \$\begingroup\$ I don't have the rep to do it myself, but you could do 04 and strike it out. \$\endgroup\$ – Bobson Dec 6 '16 at 14:09
10
\$\begingroup\$

Commodore 64 Basic, 4 bytes

1S|0

PETSCII substitution: | = SHIFT+Y

The zero page of a Commodore 64 is an area of 256 bytes of memory that can be accessed faster than the rest of RAM. Consequently, programs (such as the BASIC interpreter) use it for frequently-accessed data, and the CPU itself stores some of its internal state here. The contents are subject to change without notice.

The BASIC program above, ungolfed, is 1 SYS 0, ie. transfer execution to memory location 0. This starts executing the zero page as code. Normally, when the BASIC interpreter starts running a program, the first 16 bytes are

2F 37 00 AA  B1 91 B3 22
22 00 00 4C  00 00 00 00

so SYS 0 would execute the following

00: ROL-AND $37,A  - Undocumented opcode: rotate the value at memory location 0x37 left, and store the result in the accumulator
02: BRK            - Call the interrupt vector

The overall result is to output the BASIC READY. prompt and return control to the user. However, memory location 0x00 is the CPU's I/O direction register, and memory location 0x01 is CPU's I/O address register. If you've done something that changes these before running the program, the results can be unpredictable, ranging from outputting garbage to locking up the computer (the 0x22 usually contained in memory location 0x07, if executed as an instruction, is an undocumented HALT opcode).

Alternatively, a more reliably unpredictable program is the four-byte

1?TI

Prints the elapsed time, in jiffies (1/60 of a second), since system power-on.

\$\endgroup\$
9
\$\begingroup\$

Zsh, 5 bytes

<<<$$

Prints PID.

\$\endgroup\$
9
\$\begingroup\$

BrainfuckX and small s.c.r.i.p.t. (etc) polyglot - 2 bytes

?.

? - Randomize the value in the current cell

. - Send current cell to stdout

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

05AB1E, 2 bytes

žd

Try it online!

Outputs current microseconds from the executing machine's internal clock.

Or you could do something like this...

05AB1E, 3 bytes

A.r

Try it online!

Outputs a randomly shuffled lower-case alphabet.

Or this also works:

A.R

Try it online!

Outputs a random letter from the alphabet.

Or this also works, and is cooler:

05AB1E, 9 bytes

"ž"A.RJ.V

Try it online!

Outputs randomly one of these:

ž 23  > ža           push current hours
        žb           push current minutes
        žc           push current seconds
        žd           push current microseconds
        že           push current day
        žf           push current month
        žg           push current year
        žh           push [0-9]
        ži           push [a-zA-Z]
        žj           push [a-zA-Z0-9_]
        žk           push [z-aZ-A]
        žl           push [z-aZ-A9-0_]
        žm           push [9-0]
        žn           push [A-Za-z]
        žo           push [Z-Az-a]
        žp           push [Z-A]
        žq           push pi
        žr           push e
        žs           pop a, push pi to a digits (max. 100000)
        žt           pop a, push e to a digits (max. 10000)
        žu           push ()<>[]{}
        žv           push 16
        žw           push 32
        žx           push 64
        žy           push 128
        žz           push 256
\$\endgroup\$
8
\$\begingroup\$

C, 25 21 bytes

Thanks to pseudonym117 for saving 4 bytes.

main(i){putchar(&i);}

Compiled with gcc -o test lol.c (yeah I'm quite original with my file's name...), and ran with ./test.

It does what it says: prints the character corresponding to the memory address of i, which is defined at runtime, so it should be non-deterministic.

\$\endgroup\$
10
  • \$\begingroup\$ 1. Can you skip the & as the value of a variable on the stack isn't defined? 2. You have a constant number of things on the stack, so is the memory address if i constant? \$\endgroup\$ – Riley Nov 30 '16 at 22:14
  • 2
    \$\begingroup\$ i becomes what's normally called argc, so you're right, it will always be 1 unless there are more arguments. I can't believe I didn't rememeber that. I'm still not sure why the location changes, but if it works it works. \$\endgroup\$ – Riley Nov 30 '16 at 23:05
  • 2
    \$\begingroup\$ It changes on modern operating systems due to ASLR, a security feature designed to make it harder for exploits to guess addresses. You'll get a consistent result on some older OSes. \$\endgroup\$ – user62131 Dec 1 '16 at 1:03
  • 1
    \$\begingroup\$ You can save a little by replacing putchar with return \$\endgroup\$ – ceilingcat Dec 2 '16 at 5:15
  • 1
    \$\begingroup\$ On modern compilers with warnings for not declaring the type of a parameter, you could do: main(){printf("%d");} \$\endgroup\$ – Myria Dec 7 '16 at 20:23
8
\$\begingroup\$

Baby Language, 0 bytes



I didn't submit this originally because I thought it postdated the question. I was wrong; the language did have an interpreter created in time. It's also probably the least cheaty 0-byte solution I've seen (given that a 0-byte program is specified to do exactly what the program asks, and not for the purpose of cheating on golfing challenges).

Baby Language is specified to ignore the program it's given and do something at random. (The interpreter linked on the Esolang page generates a random legal BF program and runs it.) That seems like a perfect fit for this challenge.

\$\endgroup\$
7
\$\begingroup\$

Python 2, 29 bytes

import os
print os.urandom(9)

Sadly not the first time writing code on a smartphone.

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

Perl, 5 bytes

say$$

Outputs the process ID and a newline.

\$\endgroup\$
6
\$\begingroup\$

Ruby, 3 bytes

p$$

Try it online!

Prints the process ID.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ $. would also work Nice approach though :) \$\endgroup\$ – Jatin Dhankhar Dec 26 '16 at 15:56
6
\$\begingroup\$

Emotinomicon, 15 bytes

😀😅🎲⏬

Explanation:

😀😅🎲⏬
😀      push 0. Stack: [0]
  😅    push 1. Stack: [1]
    🎲  random[pop;pop]. Stack: [1 or 0]
      ⏬output
\$\endgroup\$
3
  • \$\begingroup\$ The language's name is Emotinomicon \$\endgroup\$ – acrolith Dec 2 '16 at 18:46
  • \$\begingroup\$ @daHugLenny How did I missed that :) \$\endgroup\$ – Roman Gräf Dec 2 '16 at 19:48
  • \$\begingroup\$ This is 4 bytes. Emotinomicon uses its own code page, meaning each emoji used is one byte. \$\endgroup\$ – Makonede Apr 29 at 16:57
5
\$\begingroup\$

Pyke, 1 byte

C

Try it here!

Outputs the current time

\$\endgroup\$
6
  • 1
    \$\begingroup\$ I'm fairly certain this is deterministic. \$\endgroup\$ – Rɪᴋᴇʀ Nov 30 '16 at 20:33
  • \$\begingroup\$ @EasterlyIrk in a deleted comment mbomb said this was ok \$\endgroup\$ – Blue Nov 30 '16 at 20:34
  • \$\begingroup\$ Oh, okay. Seems deterministic to me, but OP rules. \$\endgroup\$ – Rɪᴋᴇʀ Nov 30 '16 at 20:35
  • \$\begingroup\$ In my edit history I had a 3 byte version with proper randomness \$\endgroup\$ – Blue Nov 30 '16 at 20:35
  • 1
    \$\begingroup\$ @EasterlyIrk If the current time is deterministic, then so are pseudo-random numbers, since that's what they're seeded with. The goal is not "randomness". The goal is non-determinism. \$\endgroup\$ – mbomb007 Nov 30 '16 at 20:35
5
\$\begingroup\$

><>, 4 3 bytes

(crossed out 4 still looks like 4)

0nx

Try It Online!

Outputs some amount of 0's.

On an empty stack n throws an error and terminates the program. x chooses a random direction for the stack pointer. This means that for each 0 printed, there is a 50% chance for the program to exit.

\$\endgroup\$
3
  • \$\begingroup\$ Oh, 0xn didn't work because it pushes two zeros to begin with. Both 0nx and xn0 would work. \$\endgroup\$ – Martin Ender Nov 30 '16 at 21:13
  • \$\begingroup\$ I realised that - if go left first time, end up with 0 printed and 0 on the stack. The same happens for right, meaning that that program was deterministicly infinitely 0 output \$\endgroup\$ – Blue Nov 30 '16 at 21:16
  • \$\begingroup\$ @BlueEyedBeast This is a nice one, my version differs a little bit but same bytes; "ox \$\endgroup\$ – Teal pelican Dec 1 '16 at 9:46
5
\$\begingroup\$

MATL, 1 byte

r

Uniform random number generator between 0 and 1. The seed is randomly set for each execution of the program. Try it online!

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Same exact solution and explanation works in Pip. \$\endgroup\$ – DLosc Dec 1 '16 at 3:34
5
\$\begingroup\$

C89 with GCC/Clang, 20 bytes

The other C solution just segfaults every time when built with GCC or Clang. This, though.

main(n){puts(&n+1);}

Which looks like:

$ for _ in `seq 1 50`; do ./test_89; done
���z�U
�VW��U
�F��U
�v�f2V
��FV
���*=V
�6���U
�20wU
��
�+V
�6
   �U
��V�uU
�v��V
���K�U
��7�qU
�6S�jU
�&�WU
��wV
��6l�U
���U
�F�ߨU
�f���U
���s7V
�f��?V
��;B�U
�;��U
��GV
�� ��U
�vKV
�V?]wU
�����U
��.�U
�v"�XU
��uhpU
��LD�U
�����U
�6X�U
��M�.V
�69��U
��ԤV
���U
����U
�vx4.V
�֝+xU
�F��U
�֤BQV
��#�U
���1^U
����sU
��4�U
��AݗU

Quite a lot of unprintable junk but it's nondeterministic!

\$\endgroup\$
5
  • \$\begingroup\$ why "main(n){puts(&n+1);}" and not "main(n){puts(&n);}"? \$\endgroup\$ – user58988 Dec 2 '16 at 22:23
  • \$\begingroup\$ @RosLuP Your second option, which seems obvious to the casual observer, gives the byte at the value of n (when n is 1, putsing its address gives 1, and when n is 2, putsing its address gives 2). Adding 1 to the address of n, which should point to a 4-byte wide int, gives a junk address with a junk value stored there with a very certain number of bytes until the next NUL byte. This behaviour is reproducible between GCC and Clang and completely beyond me. I think I'll go ask on StackOverflow. \$\endgroup\$ – cat Dec 2 '16 at 22:30
  • \$\begingroup\$ i read "puts(&n)" in this way: it give to puts the address of n, suppose that n=0x01020304 puts would print converted in chars 04 03 02 01 or reverse of that \$\endgroup\$ – user58988 Dec 2 '16 at 22:41
  • 1
    \$\begingroup\$ Remember your n is still initialized with what's normally called argc which is 0 in your general test case, so with &n, puts gets a quite deterministic pointer to a '\0' byte resulting in an empty string (assuming pointer size == integer size and all that stuff). &n+1 however is the address of what's normally called argv (at least on ABIs that pass parameters on the stack in reverse order instead of registers, and with a stack that grows from high to low addresses), which, assuming ASLR, should be a different pointer every time. \$\endgroup\$ – Guntram Blohm Dec 5 '16 at 15:11
  • \$\begingroup\$ @GuntramBlohm You're right and that's very interesting, although for me pointers are 8 bytes and ints are 4 bytes. \$\endgroup\$ – cat Dec 5 '16 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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