# Question
Title: 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.

## 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>
```

# Answer
# 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.
> 46 votes

# Answer
# 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]

```
> 121 votes

# Answer
# 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.
> 68 votes

# Answer
# Java 7, ~~33~~ ~~30~~ 27 bytes

```
int a(){return hashCode();}

```

Because Java.
> 67 votes

# Answer
# R, 1 byte

```
t

```

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

# Answer
# 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.
> 34 votes

# Answer
## 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.)
> 33 votes

# Answer
# 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 `@`.
> 30 votes

# Answer
# 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.
> 25 votes

# Answer
## 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.
> 25 votes

# Answer
# 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>
```
> 23 votes

# Answer
# 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 **A**ddress **S**pace **L**ayout **R**andomization 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.
> 20 votes

# Answer
# 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):

---

# Pyth, 2 bytes

```
OT

```

Explanation:

```
 T 10
O  Random integer in [0, 10]

```

Try this *boooooooooooooooring* version instead `>:(`
> 18 votes

# Answer
## Python 2, 11 bytes

```
print id(1)

```
> 13 votes

# Answer
# Bash (procps-ng), 2 bytes

```
ps

```

`$$` is also a solution.
> 13 votes

# Answer
# 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.
> 13 votes

# Answer
## 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"

```
> 12 votes

# Answer
# Notepad, 1 keystroke

`F5`

Pressing `F5` inserts the time and date in the format `(h)h:mm XM (m)m/(d)d/yyyy`. For example: `12:00 AM 1/1/1970`
> 11 votes

# Answer
# 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.
> 10 votes

# Answer
# Zsh, 5 bytes

```
<<<$$

```

Prints PID.
> 9 votes

# Answer
## 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.
> 9 votes

# Answer
## 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
> 9 votes

# Answer
# 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

```
> 8 votes

# Answer
# Perl, 5 bytes

```
say$$

```

Outputs the process ID and a newline.
> 7 votes

# Answer
# Python 2, 29 bytes

```
import os
print os.urandom(9)

```

Sadly not the first time writing code on a smartphone.
> 7 votes

# Answer
## Pyke, 1 byte

```
C

```

Try it here!<sup>\[broken\]</sup>
Try it Online!

Outputs the current time
> 6 votes

# Answer
## Ruby, 3 bytes

```
p$$

```

Try it online!

Prints the process ID.
> 6 votes

# Answer
# Groovy, 9 bytes

`{print{}}`

Outputs:

`Script1$_run_closure1@2c8ec01c`

Because it outputs the memory address of the closure it is non-deterministic.
> 6 votes

# Answer
# Emotinomicon, 15 bytes

Explanation:

```
⏬
      push 0. Stack: [0]
      push 1. Stack: [1]
      random[pop;pop]. Stack: [1 or 0]
      ⏬output

```
> 6 votes

# Answer
## \>\<\>, ~~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.
> 5 votes

# Answer
# Mathematica, 6 bytes

```
Date[]

```

Pretty self-explanatory. (This function was superseded by `DateList[]` in later versions, but `Date[]` still runs.)

For 8 bytes one can also use `Random[]` (itself a legacy function).
> 5 votes

# Answer
# 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!
> 5 votes

# Answer
# PHP, 12 bytes

```
<?=uniqid();

```

Outputs a unique ID `583f4da627ee3` based on the current time in microseconds.
> 5 votes

# Answer
# Borland C on Windows, 12 bytes

```
m(){puts();}

```

I rewrote it because they said it's possible to use one function. The compiler doesn't check the argument so it compiles it; but `puts` sees an unknown address and begins to print what that address points to until it finds the byte `0x00`. It would not work if that address was out of memory, but here it prints something.
> 5 votes

# Answer
# 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!
> 5 votes

# Answer
# 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?)
> 5 votes

# Answer
# Knight, 2 bytes

```
`R

```

Try it online!

```
`   Run as a shell command:
R   A random integer

```

The non-deterministic output is to stderr. The C interpreter implicitly converts the number to string and tries to run it as a shell command. With very high chance (if not 100%), such a command or executable does not exist in PATH, and an error message that looks like `sh: <some random number>: command not found` is printed to stderr.

This is shorter than the straightforward `O R` which prints the random number to stdout.
> 5 votes

# Answer
# 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.
> 4 votes

# Answer
# Japt, 1 byte

```
Ð

```

Test it online!

### How it works

When Japt is compiled to JavaScript, it replaces `Ð` with `new Date(`. The close-paren is automatically added by the interpreter, and the result of the last expression is automatically printed, so this prints the current date/time.

An alternate solution would be `Mr`, which uses `Math.random`. Japt also has the variable `K` set to `Date` (no clue why I did that, it's almost entirely useless), which I guess makes `K` a valid function entry.
> 4 votes

# Answer
# C#, ~~36~~ 22 bytes

```
a=()=>a.GetHashCode();

```

Yay.
> 4 votes

# Answer
# 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.
> 4 votes

# Answer
## C++, 26 19 Bytes

```
std::cout<<new int;

```

Returns a different memory address each time it's run
> 4 votes

# Answer
# 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.
> 4 votes

# Answer
# , 5 bytes

```
main;

```

Try it online!
> 4 votes

# Answer
# Julia, 4 bytes

```
rand

```

Try it online!

```
time

```

Try it online!
> 4 votes

# Answer
# 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.
> 3 votes

# Answer
# 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())`
> 3 votes

# Answer
# 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")() );
  }
}

```

Or try it on Ideone.
> 3 votes

# Answer
# 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`.
> 3 votes

# Answer
# APL, 2 bytes

```
?9

```

This uses APL's roll (`?`) operator. The program prints a pseudo-random number between 1 and 9.
> 3 votes

# Answer
## PHP 10 bytes

```
<?=rand();

```

Prints a random number between 0 and getrandmax(). Which may vary based on what computer it's run on.
> 3 votes

# Answer
# 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

```
> 3 votes

# Answer
# 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)*
> 3 votes

# Answer
# 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!
> 3 votes

# Answer
# Taxi, ~~222 220~~ 218 bytes

```
Go to Heisenberg's:w 1 r, 3 r, 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 r, 1 l.Pickup a passenger going to Post Office.Go to Post Office:n, 1 l, 1 r.Go to Taxi Garage:n 1 r, 1 l, 1 r.

```

Prints a random number. The spec does not give any details on what number should be. The last statement can be omitted (producing 184 bytes) if you don't mind the code giving an error after printing the output.

Try it online!
> 3 votes

# Answer
## 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).
> 3 votes

# Answer
## Wumpus, 4 bytes

```
UFO@

```

Try it online!

Outputs a uniformly random choice of **2**, **5** or **8**.

### Explanation

Apart from a regular stack, Wumpus also has 20 registers which are arranged around the faces of an icosahedron. You can imagine the icosahedron as a d20 resting on a table: the face touching the table is the "active" face (i.e. the register that can currently be interacted with). Also, every face has an index from **1** to **20**. Initially, the active face is **1** and the three adjacent faces are **2**, **5** and **8** (see the README in the Wumpus repo for the full net).

```
U   Randomly tip the icosahedron onto one of the three adjacent faces, i.e.
    change the active faces to either 2, 5 or 8.
F   Push the index of the currently active face.
O   Output as a decimal integer.
@   Terminate the program.

```

Alternatively:

```
DFO@

```

This one completely randomises the orientation of the icosahedron, so it prints a random number from **1** to **20**, inclusive.
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# 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:
> 3 votes

# Answer
# PARI/GP, 2 bytes

```
\s
```

Attempt This Online!

`\s` prints the state of the PARI stack and heap, which is non-deterministic.

**Example output:**

```
 Top : 7fadf82bd000   Bottom : 7fadf7b1be00   Current stack : 7fadf82bcfb8
 Used :                         9  long words  (0 K)
 Available :                    999991  long words  (7808 K)
 Occupation of the PARI stack :   0.00 percent
 1 objects on heap occupy 9 long words

 10 variable names used (10 user + 0 private) out of 65535

```
> 3 votes

# Answer
## JavaScript (full program), 12 bytes

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

```
throw Date()

```
> 3 votes

# Answer
# Brachylog, 3 bytes

```
9$?

```

Try it online!

### Explanation

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

# Answer
# 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

```
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# CJam, 2 bytes

```
et
```

> * You can rely on the program being run at a different (unknown) time each execution.

Yeah, that one. `et` is a single built-in that returns the array `[YYYY M D h m s ms W Z]`, printed as `YYYYMDhmsmsWZ`.
> 2 votes

# Answer
# Ruby, 14 bytes

```
p ?..object_id

```

Returns object id of the string '.'
> 2 votes

# Answer
# TI-Basic, 2 bytes

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

```
getTime

```
> 2 votes

# Answer
# 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
    }
}

```
> 2 votes

# Answer
# Braingolf, 2 bytes

```
2r

```

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

# Answer
# 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 (BrainFl*ak* is a stack, BrainFl*ueue* 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

```
> 2 votes

# Answer
# Rust, 28 bytes

```
fn main(){print!("{:p}",&1)}

```

Try it online!

Takes a reference to a temporary `1` and prints the address.

---

# Rust, 17 bytes

```
fn main(){0-1u8;}

```

Try it online! (requires the `-A const_err` compiler flag)

This is a bit sketchier, and I'm not sure whether it counts. The non-deterministic output is to STDERR, and the non-determinism arises only based on the value of an environment variable.

This program attempts to compute `0 - 1`, where both integers have type `u8` (the default is `i32`, which won't cause an overflow because it's signed). By default, Rust compiles the file in debug mode, in which arithmetic overflow causes a panic instead of wrapping. When a program panics, it will print a stack trace if the environment variable `RUST_BACKTRACE` is set to 1, hence the non-determinism.
> 2 votes

# Answer
## Keg, 1 byte

```
~

```

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

# Answer
# \>\<\> (Fish), 4 bytes

```
1n0x

```

Try it

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

# Answer
# Uiua, 1 byte

Try it!

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

# Answer
# C (gcc), 24 bytes

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

```

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

Try it online!
> 2 votes

# Answer
# Python, 11 bytes

```
1/(id(2)%3)

```

Attempt This Online!

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

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

# Answer
**Wirefunge \- 2 bytes**

```
¿>

```

¿ - Randomized output every iteration

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

# Answer
## Clojure, 4 bytes

```
rand

```

The obvious answer. `rand` is a core function that returns a floating-point number between 0 and 1 (exclusive) when called without any arguments.

I don't think it gets any shorter than this in Clojure.
> 1 votes

# Answer
# Perl 6, 13 bytes

```
put Bool.pick

```
> 1 votes

# Answer
## Marbelous, 5 bytes

```
FF
??

```

Prints a single random byte. `FF` creates a marble with value `255`. That marble falls through the random number generator `??` which replaces the marble's value with a random value between `0` and `255` inclusive. When the marble falls off the bottom of the board, it gets printed to STDOUT as a byte.
> 1 votes

# Answer
## R, 7 bytes

The Student t Distribution

```
rt(1,1)

```

The Exponential Distribution

```
rexp(1)

```

Two options how to generate a random number with the shortest code.
> 1 votes

# Answer
# ForceLang, 11 bytes

```
random.rand

```

A function that, when called with no arguments, produces a random rational of the form `n/2^80`, where `n` is an integer on `[0,2^80-1]`.

(If you give it a positive integer argument `m` \[which must be strictly less than 65536, not that you'll ever reasonably need to go nearly that high\] it will produce a random rational of the form `n/2^m`, where `n` is an integer on`[0,2^m-1]`)
> 1 votes

# Answer
# Thue, 17 bytes

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

```

Randomly prints either nothing, or the digit `1`.
> 1 votes

# Answer
## T-SQL 15 bytes

```
print getdate()

```
> 1 votes

# Answer
# Minkolang v1.5, 4 bytes

```
lhN.

```

`l` pushes `10`. `h` pushes a random integer from `0` to `10`, `N` outputs it and `.` ends program. Simple, eh?

Try it online!
> 1 votes

# Answer
# Shell, 2 bytes

`ps`

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

# Answer
# SmileBASIC, 6 bytes

```
?TIME$

```

Prints the current time.
> 1 votes

# Answer
# tcl, 3

Must be run on an interactive shell

```
pwd

```

Gets the current working directory.

Or alternatively

```
pid

```

Gets the current process identifier

**Demo:** Go to https://www.tutorialspoint.com/execute\_tcl\_online.php and in the green area, type

```
tclsh

```

Then type

```
pwd

```

and

```
pid

```
> 1 votes

# Answer
## Alice, 4 bytes

```
2Uo@

```

Try it online!

Prints a single byte, either 0x00 or 0x01, with 50% probability each.

```
2    Push 2.
U    Get a random integer in [0,1].
o    Output that integer as a byte.
@    Terminate the program.

```
> 1 votes

# Answer
# Fourier, 3 bytes

```
9ro

```

Outputs a random number from 0 to 9.

Try it online!
> 1 votes

# Answer
# Add++, 6 bytes

The most random I could get for 6 bytes

```
+9  Set the accumulator to 9
R   Set the accumulator to a random integer between 0 and 9
O   Output the result

```

I could change `R` to `R-9` to double the randomness for 2 extra bytes.
> 1 votes

# Answer
# Chip, 2 + 3 = 5 bytes

+3 bytes for `-w`

```
g?

```

Gives infinite-length output. Each byte of output is independent, and is either NUL `\x00` or '@' `\x40`.

There are eight equivalent Chip programs that are like this, from `a?` (which prints `\x00` or `\x01`) to `h?` (which prints `\x00` or `\x80`). `g?` is just the most visible option.

For each of these programs, the letter `a` through `h` defines the index of a bit of the output, and `?` produces a random value to set it to. The two elements may be provided in any order; they must only touch each other on a 2D plane.

Try it online! The TIO includes the `-cN` flag. This flag is not necessary, but cuts off the program after N bytes. Try without the cutoff if you wish, but TIO's limit is at 128KiB.
> 1 votes

# Answer
# Flobnar, ~~5~~ 4 bytes

<sup>-1 byte thanks to @JoKing</sup>

```
0?.@

```

Try it online!
> 1 votes

# Answer
# Ink, 5 bytes

```
{~a|}

```

Try it online!

Either outputs "a" or nothing.
> 1 votes

# Answer
## Perl 6, 7 bytes

```
say now

```

about `now`
> 1 votes

# Answer
# Japt, 1 byte

```
K

```

Try it online!
> 1 votes

# Answer
# 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.

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# .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.
> 1 votes

# Answer
# EmojiCoder, 44 bytes

Try it online!

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

# Answer
# Barrel, 2 bytes

```
|n

```

Gets a random integer with `|` and prints it as a number with `n`.
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 19 bytes

```
 output =date()
end

```

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

Try it online!
> 1 votes

# Answer
# APOL, 1 byte

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

# Answer
# Knight, 3 bytes

```
O R

```

Try it online!

Not a complicated answer.
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~15~~ 14 bytes

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

```
 exit('w')
end

```

Try it online!
> 1 votes

# Answer
# Vyxal, 2 bytes

```
9℅

```

Try it online!

Outputs a random integer from 0 to 9.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Swift, 8 bytes

```
[][0]

```

Try it online!

Literally all this does is create an empty array (which the compiler miraculously infers to be of type `[Any]`) and attempts to access its first element, which obviously does not exist because the array is empty. Unlike some other languages I can name, Swift actually makes sure you don't try to use things that don't exist, and so this subscript calls `fatalError(_:file:line:)`, which (among other, more useful things) prints out memory addresses, thereby meeting the criteria for non-determinism.
> 1 votes

# Answer
# 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.
> 0 votes

# Answer
## 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.
> 0 votes

# Answer
## Batch, ~~6~~ 4 bytes

```
time

```

Needs to be run with `<nul` which is apparently permissible.
> 0 votes

# Answer
## Swift 3, 13 bytes

```
print(Date())

```
> 0 votes

# Answer
## 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.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# Microscript, 2 bytes

`r9`

Produces a random integer on `[0,8]`
> 0 votes

# Answer
# Mouse2002, 7 bytes

```
&RAND !

```
> 0 votes

# Answer
# ASP VBScript, 43 bytes

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

```

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

# Answer
# HSPAL, 18 bytes

```
26FFFF
400000
120000

```

Prints a random 16-bit integer.
> 0 votes

# Answer
# Math++, 5 bytes

```
$rand

```

Produces a random 64-bit float
> 0 votes

# Answer
# C, 22 bytes

```
f(){putchar(time(0));}

```
> 0 votes

# Answer
# 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.)
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# Pyt, 1 byte

```
ɽ

```

Returns a random 32-bit integer.

Also 1 byte: `ɹ`, .
> 0 votes

# Answer
# 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!
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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`.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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
> 0 votes

# Answer
# Pip, 3 bytes

```
RR9

```

Attempt This Online!

Prints a random integer from 0 to 9
> 0 votes

# Answer
# Thunno 2, 2 bytes

Attempt This Online!

Outputs a random integer from 1 to 9.
> 0 votes

# Answer
# 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).
> 0 votes

---
Tags: code-golf, random
---


title: Can I follow this recipe?

text:
# Question
Title: Can I follow this recipe?
You work in a kitchen which has a peculiar rule. When you mix something into a pot you must always add at least one new ingredient.

So you can add pasta, oil, salt then pesto, but not pasta, pesto, salt and oil since pesto already contains salt and oil. You only have one pot per dish, so you can't mix ingredients in one pot and then dump that into another.

So we can say that mixing is an associative partial binary operation \\$\otimes\\$, which takes the union of two sets of ingredients, but only operates on pairs where the second set contains some element not in the first, so

\\$ \\{1,2\\}\otimes\\{6,2\\} = \\{6,1,2\\} \\$

but

\\$ \\{1,2,3\\}\otimes\\{1,3\\} \\$

is undefined.

Now this rule is annoying because it means you have to be careful about the order you combine things. Sometimes there are even recipes can't be followed because there's no way to mix all the parts without breaking the rule.

A recipe can be followed if there is a way to order the parts so that each part contains an ingredient not found in prior parts.

So if the parts of the recipe are:

\\$ \\{1,2,3,5\\},\\,\\{5\\},\\,\\{2,5,6\\},\\,\\{1,2,4,5\\},\\,\\{3,5\\} \\$

then they can be ordered:

\\$ \\{5\\}\otimes\\{3,5\\}\otimes\\{1,2,3,5\\}\otimes\\{2,5,6\\}\otimes\\{1,2,4,5\\} \\$

However

\\$ \\{1,2,3,5\\},\\,\\{5\\},\\,\\{2,4,5\\},\\,\\{1,2,4,5\\},\\,\\{3,5\\} \\$

cannot be ordered without breaking the kitchen's rule.

## Task

Take as input sets of positive integers representing parts of a recipe. Output one of two distinct consistent values depending on whether the input represents a possible or impossible recipe.

You may assume there is at least one part in the input, and at least one ingredient in every part.

This is . The goal is to minimize the size of your source code as measured in bytes.

## Test cases

```
{9,2,3} -> True
{5},{5} -> False
{2},{9} -> True
{5},{3,5},{2,5,6},{1,2,4,5},{1,2,3,5} -> True
{1,2,3,5},{5},{2,4,5},{1,2,4,5},{3,5} -> False
{5},{5},{9,5} -> False
{1,2,3,5},{5},{2,4,5},{1,2,4,5},{3,5},{9,5} -> False

```

# Answer
# Jelly,  ~~11~~  10 bytes

-1 using Jonathan Allan's observation that we can check if a new ingredient is added each step by seeing if the cumulative ingredient sets are unique (by checking invariance over deduplication), , instead of check if the length is increasing (3 bytes).

```
Œ!œ|\QƑ$€Ẹ

```

Try It Online!

---

### Original, 11 bytes

```
Œ!œ|\ẈIẠƲ€Ẹ

```

Try It Online!

### Explanation

You can find a video explanation of this solution as well here!

```
Œ!œ|\ẈIẠƲ€Ẹ    Main Link
Œ!             all permutations
         €     for each (permutation)
        Ʋ      last three links:
    \          - cumulative reduce on:
  œ|             - set union
     Ẉ         - length of each (ingredient set at each step)
      I        - increments
       Ạ       - is any non-zero?
          Ẹ    any?

```
> 7 votes

# Answer
# Python, 72 bytes

```
f=lambda x,s={0}:len(x)==len({*x})*any(f({*x}-{i},s|i)for i in x if i-s)

```

Attempt This Online!

Takes input as a list of `frozenset`s

---

## Original, 80 bytes

```
f=lambda x,s={0}:len(x)==len({*x})*any(f({*x}-{i,()},s|{*i})for i in x if{*i}-s)

```

Attempt This Online!

This one handles empty parts
> 6 votes

# Answer
# Jelly,  ~~11~~  10 bytes

-1 using hyper-neutrino's observation that we can use multiset-union, `œ|` to get the prefix unions mentioned in my original (and there is no need to deduplicate these).

```
Œ!œ|\QƑ$€Ẹ

```

**Try it online!** Or see the test-suite.

---

### Original, 11 bytes

```
Œ!;\Q€QƑƊ€Ẹ

```

**Try it online!** Or see the test-suite.

### How?

Any order that works will have a distinct list of prefix unions (since each step adds at least one new ingredient):

```
Œ!;\Q€QƑƊ€Ẹ - Link: list of lists of ingredients, Recipe
Œ!          - all permutations of {Recipe}
         €  - for each Ordering:
        Ɗ   -   last three links as a monad - f(Ordering):
   \        -     cumulative reduce by:
  ;         -       concatenate
    Q€      -     deduplicate each
      QƑ    -     is invariant under deduplication?
          Ẹ - any?

```
> 5 votes

# Answer
# Vyxal 3, 6 bytes

```
ṖḌᶳRᵞu

```

Try it Online!

Thank you to @lyxal for porting my solution to Vyxal 3, which has some nice features that save us a lot of bytes.

### Explanation

```
ṖḌᶳRᵞu    Full Program
Ṗ         Permutations
 Ḍ        Does any satisfy? (opens a structure, closed by } but can be omitted)
  ᶳR      Cumulative reduce over set union
    ᵞu    Invariant over uniquify

```

This is the same idea as the original solution (below) which is the same as the joint Jelly solution that Jonathan Allan and I got by combining our approaches.

---

### Vyxal 2, Flagless 9 bytes

```
Ṗƛɖ∪¨=U;a

```

Try it Online!

### Explanation

You can find a video explanation of this solution as well here!

```
Ṗƛɖ∪¨=U;a    Full Program
Ṗ            all permutations
 ƛ     ;     for each (permutation):
  ɖ          - cumulatively reduce on:
   ∪           - set union
    ¨=       - is it the same when
      U        - uniquified?
        a    any?

```

This is the same idea as the 10-byte Jelly solution formed from the merging of my cumulative reduce on union and Jonathan Allan's invariance over uniquification.

Vyxal saves two bytes here by having a one-byte built-in for getting all permutations and for set union, but loses one of those bytes back by requiring two bytes for invariance.

---

The following also works:

### Vyxal `G`, 7 bytes

```
Ṗƛɖ∪¨=U

```

Try it Online!

Here, we shift the use of `a` to check if any permutation works and instead map the function over all of them to get a list of zeroes (for when the ordering is invalid) and ones (for when it is valid). The `G` flag returns the maximum value which serves the same purpose. Even if flags are counted 1:1, we save a byte here because now we can remove the `;` that was previously required to close the map lambda.
> 5 votes

# Answer
# Brachylog, ~~11~~ 9 bytes

```
p{a₀cd}ᶠ≠

```

### Explanation

Brachylog is a terse prolog. So we are defining a constraint and checking if the input matches it.

```
p{a₀cd}ᶠ≠
p           find a Permutation where
 {    }ᶠ      all the  (Find all)
  a₀          prefixes (Adfix variant 0: prefix)
    cd        when Concatenated and Deduplicated
        ≠     are unique

```

## Old solution

```
p{h;.≠&cd}ˡ

```

### Explanation

Brachylog is a terse prolog. So we are defining a constraint and checking if the input matches it.

```
p{h;.≠&cd}ˡ
p              Does there exist a Permutation of the input for which
 {       }ˡ    we can apply the following Left fold:
      &cd      Concatenate the 2 items and Deduplicate them with the additional
  h            constraint that if we take the first item (Head) it
   ;.≠         does not equal our result

```

Try it online!
> 4 votes

# Answer
# Haskell, ~~88~~ ~~85~~ ~~67~~ 60 bytes

*-7 bytes thanks to Wheat Wizard.*

```
import Data.List
any(((==)<*>nub).scanl1 union).permutations

```

Try it online!

Using Jonathan Allan's observation that cumulative ingredient sets being unique means new ingredients are being added at every step.
> 3 votes

# Answer
# JavaScript (Node.js), 82 bytes

```
f=x=>x+x?x.some((t,i)=>t.some(u=>!i.flat().includes(u),i=x.filter(_=>i--))&f(i)):1

```

Try it online!

Base case `[]` or `[[]]`

Find element t that contains a new element and x\t is possible, then append t
> 2 votes

# Answer
# JavaScript (ES6), 75 bytes

*-3 thanks to @tsh*

Returns a Boolean value.

```
f=(a,m)=>a<1||a.some(b=>b.map(v=>M|=1<<v,M=m)&&M!=m&f(a.filter(c=>c!=b),M))

```

Try it online!
> 2 votes

# Answer
# AWK, 65 64 bytes

```
{for(i=NF;i;i--)r=_[$i]++?1:r}!NF{r=_[""]++?1:r}END{print r?0:1}

```

Try it online!

Will print `0` for `false` and `1` for `true`.
> 2 votes

# Answer
# 05AB1E, 13 bytes

```
œεηε˜Ùg}¥ĀP}à

```

Try it online or verify all test cases.

**Explanation:**

```
œ        # Get all permutations of the (implicit) input-list of lists
 ε       # Map over each inner permutation
  η      #  Get all prefixes of this permutation
   ε     #  Map over each prefix:
    ˜    #   Flatten this list of lists
     Ù   #   Uniquify it
      g  #   Pop and push its length
   }¥    #  After the inner map: get the forward-differences
     Ā   #  Check for each whether it's NOT 0
      P  #  Check that all are truthy
 }à      # After the outer map: check if any is truthy
         # (which is output implicitly as result)

```
> 2 votes

# Answer
# Nekomata \+ `-e`, 7 bytes

```
ᶦ{ĕ~f}z

```

Attempt This Online!

```
ᶦ{ĕ~f}z
ᶦ{   }      Repeat the following arbitrarily many times:
  ĕ             Take an item out from the list
                e.g. [[],[3],[2,6],[1,2,4],[1,2,3]] -> [[],[3],[1,2,4],[1,2,3]], [2,6]
   ~            Choose an element from the item
                e.g. [2,6] -> 6
    f           Check that the remaining (nested) list does not contain the element
                If so, return the list
                e.g. [[],[3],[1,2,4],[1,2,3]] 6 -> [[],[3],[1,2,4],[1,2,3]]
      z     Check that the result contains only one element

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~59~~  45 bytes

```
Or@@UnsameQ@@@FoldList@Union/@Permutations@#&

```

-14 thanks to @att
Try it online!
> 2 votes

# Answer
# Charcoal, 23 bytes

```
⊞υθＦ⊖Ｌθ≔ΣＥθＥΦυ⁻κμ⁺μκυ¬υ

```

Attempt This Online! Link is to verbose version of code. Outputs an inverted Charcoal boolean, i.e. `-` if the recipe is impossible, nothing if it is impossible. Explanation:

```
⊞υθ

```

Start with recipes with each part as their ingredient.

```
Ｆ⊖Ｌθ

```

Loop over the remaining number of parts.

```
≔ΣＥθＥΦυ⁻κμ⁺μκυ

```

For each part, find the recipes for which that part includes a new ingredient, add the part to the recipe, and create a new list of augmented recipes.

```
¬υ

```

Output whether the recipe was impossible.

22 bytes if the empty part is disallowed:

```
⊞υ⟦⟧Ｆθ≔ΣＥθＥΦυ⁻κμ⁺μκυ¬υ

```

Attempt This Online! Link is to verbose version of code. Explanation: As above but starts with a recipe with no parts and then loops for the given number of parts.
> 1 votes

# Answer
# Ruby, 59 bytes

```
f=->l{l==[[]]||l==l|l&&(l-=[[]]).any?{|x|f[l.map{|z|z-x}]}}

```

Try it online!

### Why?

* If the list only contains an empty set, then it's true.
* If the list contains duplicates, then it's false.
* In any other case, we can remove the empty set from the list and check if there is a set that we can subtract from all the other sets in the list to produce a valid list.
> 1 votes

# Answer
# APL(Dyalog Unicode), 45 bytes SBCS

```
{⍺←⍬⋄0=⍴⍵:1⋄(⍵≡∪⍵)∧∨/((⍺≢⍺∪⊢)∧(⍺∪⊢)∇⍵~⊂∘⊢)¨⍵}

```

Try it on APLgolf!
> 0 votes

---
Tags: code-golf, decision-problem
---


title: Contract a tensor

text:
# Question
Title: Contract a tensor
# Introduction

Tensor contraction is an operation that can be performed on a tensor. It is a generalization of the idea of the trace of a matrix. For example, if we have a rank-2 tensor (a matrix) and we contract along both of its axes, we take the sum of each entry in which the indices of these axes are equal. In this case we sum the entries at (0,0), (1,1), (2,2), and so on to get a rank-0 tensor (a scalar), which in this case, is the trace of the matrix.

As another example, if we have a rank-4 tensor (a 4-dimensional array), contraction will output a rank-2 tensor (a matrix). If we are contracting over the first and third axes, the axes in the result correspond to the remaining axes. The entry at (3,4) of the output is produced by summing the entries of the original at (0,3,0,4), (1,3,1,4), and so on.

# Challenge

Given a rank-n tensor and two distinct axes, perform tensor contraction along those axes.

## Input

You may take the tensor in any reasonable format such as an n dimensional array or list-of-lists-of-...-lists. The tensor is always guaranteed to have equal length (at least 1) along every axis. You may take the axes as either 0-indexed or 1-indexed, as well as in either direction (0 or 1 may refer to the first axis in a list-of-lists or the most nested axis).

## Output

Any reasonable format for an rank-(n-2) tensor. In particular, a rank-0 scalar cannot be nested in an array.

# Examples

Using 0-indexing:

```
[[0, 1, 2],
 [3, 4, 5],
 [6, 7, 8]], 0, 1 -> 12 # trace of the matrix

[[[4, 8, 4],
  [1, 6, 9],
  [2, 8, 2]],
 [[8, 4, 9],
  [7, 9, 2],
  [0, 4, 4]],
 [[2, 7, 7],
  [6, 3, 0],
  [3, 8, 8]]], 0, 1 -> [14, 25, 14]

[[[4, 8, 4],
  [1, 6, 9],
  [2, 8, 2]],
 [[8, 4, 9],
  [7, 9, 2],
  [0, 4, 4]],
 [[2, 7, 7],
  [6, 3, 0],
  [3, 8, 8]]], 0, 2 -> [15, 10, 14] # different answer along different axes

[[[[8, 5],
   [7, 9]],
  [[2, 0],
   [6, 0]]],
 [[[8, 3],
   [2, 2]],
  [[1, 3],
   [9, 1]]]], 0, 2 -> [[10,  7],
                       [11,  1]]

[[[[[7]]]]], 1, 4 -> [[[7]]] # contraction always reduces rank by 2

```

Standard loopholes are forbidden. As this is , shortest program wins.

# Answer
> 5 votes
# APL (Dyalog Unicode), 23 bytes

```
+/⊢⍉⍨-⍨⍥≢∘⍴⌊{⍋⍋⍺∊⍨⍳≢⍴⍵}

```

Follows a golf suggested by Marshall and Adam. My original answer that shows the idea better:

```
{+/⍺⍉⍨(⍳r-2)@(⍵~⍨⍳r)⊢(r-2)@⍵⊢0⍴⍨r←⍴⍴⍺}

```

Matrix on the left, the two axes on the right. Works by noticing that tensor contraction on two axes given a tensor A is equivalent to dyadic transposition with rank(A)-2 in place of axes and iota everywhere else. Then we sum once by trailing axis. Transposition reduces rank by one, sum on trailing axis also reduces rank by one. Hence the resulting tensor has rank of rank(A)-2. Assumes quad IO of zero.

# Answer
> 5 votes
# Python \+ NumPy, 24 bytes

-3 bytes thanks to @Mukundan314.

```
lambda a,i:a.trace(0,*i)

```

Attempt This Online!

# Answer
> 3 votes
# JavaScript (Node.js), 115 bytes

```
f=(m,x,y,j)=>(r=m.map?.((n,i)=>f(n,x-1,y-1,x?j:i)),y?x?r:r.reduce(a=(u,v)=>u.map?.((w,i)=>a(w,v[i]))??u+v):r[j])??m

```

Attempt This Online!

# Answer
> 2 votes
# Charcoal, ~~103~~ ~~82~~ 81 bytes

```
≔ＬθεＷ⁺υΣθ«≔ιθ→»≔Ｅθ⟦⟧δＵＭＥθ﹪÷κＸε⮌…·⁰ⅈε∧⁼§ιη§ιζ⊞Ｏ§δ↨Φι∧⁻μη⁻μζε§θκＵＭδΣιＦⅈ≔⪪δεδ⭆¹⊟⮌§δ⁰

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
≔Ｌθε

```

Get the size of the tensor.

```
Ｗ⁺υΣθ«≔ιθ→»

```

Flatten the tensor into a list and get `1` less than the number of dimensions.

```
≔Ｅθ⟦⟧δ

```

Create a temporary holding list of lists for the elements of the tensor that will be summed to make the contracted tensor. This list is still the same size as the flattened tensor for now.

```
ＵＭＥθ﹪÷κＸε⮌…·⁰ⅈε∧⁼§ιη§ιζ⊞Ｏ§δ↨Φι∧⁻μη⁻μζε§θκ

```

For each element of the tensor, calculate whether it contributes to the contracted tensor, and if so, append that element to the relevant list element.

```
ＵＭδΣι

```

Sum each of the lists.

```
Ｆⅈ≔⪪δεδ

```

Unflatten the list back into a tensor of the original dimension.

```
⭆¹⊟⮌§δ⁰

```

Retrieve the first element of the first element to produce the final result.

Previous 103-byte version was a backport to TIO of a 79-byte version using my experimental multidimensional indexing branch:

```
≔θδＷ⁺υδ«≔⌊δδ→»≔Ｘ⁰⊕↔…⌊θ¹εＦΦＥＸＬθⅈ﹪÷ιＸＬθ…⁰ⅈＬθ⁼§ιη§ιζ«≔⁺⟦⁰⟧Φι∧⁻λη⁻λζγ≔⊟γβ≔εαＦγ≔§ακα≔θγＦι≔§γκγ§≔αβ⁺§αβγ»⭆¹⊟ε

```

Try it online! Link is to verbose version of code. Explanation:

```
≔θδＷ⁺υδ«≔⌊δδ→»

```

Calculate the number of dimensions of the input tensor.

```
≔Ｘ⁰⊕↔…⌊θ¹ε

```

Generate a list of a zero tensor of two fewer dimensions as the initial value of the result tensor.

```
ＦΦＥＸＬθⅈ﹪÷ιＸＬθ…⁰ⅈＬθ⁼§ιη§ιζ«

```

Loop over the multidimensional indices of all the elements of the tensor where the coordinates in the two given axes are identical.

```
≔⁺⟦⁰⟧Φι∧⁻λη⁻λζγ≔⊟γβ≔εαＦγ≔§ακα

```

Get the parent list of the corresponding element of the result tensor.

```
≔θγＦι≔§γκγ§≔αβ⁺§αβγ

```

Get the element of the input tensor and add it to that result element.

```
»⭆¹⊟ε

```

Pretty-print the final result. (This is to show that the result is a single element when the input has two dimensions, as otherwise the output would be indistinguishable.)

Explanation of the 79-byte multidimensional indexing version:

```
≔θδＷ⁺υδ«≔⌊δδ→»

```

Calculate the number of dimensions of the input tensor as before.

```
≔×⁰…⌊θ¹ε

```

Generate a list of a zero initial result tensor. (This is slightly shorter because `Times` fully vectorises on that branch but it only vectorises over single dimensional arrays on TIO.)

```
ＦＥＸＬθⅈ﹪÷ιＸＬθ…⁰ⅈＬθ«

```

Loop over the multidimensional indices of the input tensor.

```
≔⁺⟦⁰⟧Φι∧⁻λη⁻λζδ

```

Get the multidimensional index of the result element.

```
¿⁼§ιη§ιζ§≔εδ⁺§εδ§θι

```

Update that element if the coordinates in the two given axes are identical.

```
»⭆¹⊟ε

```

Pretty-print the final result.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 14 bytes

```
TensorContract

```

Axes are 1-indexed.
-5 thanks to @att
Try it online!

# Answer
> 1 votes
# Pyth, 38 bytes

```
.N?T:RtTtYN?tY:CN1Y?sIssNs.e@bkN:CMNT2

```

Try it online!

Defines a function `:` which takes three inputs: a nested list, first axis, and second axis. This assumes that the first axis is less than the second axis.

### Explanation

The function operates recursively. The two axis inputs are `T` and `Y`. There are four cases to consider:

* In the base case `T=0`, `Y=1`, and the matrix has depth 2. In this case we simply take the trace of the matrix, which is straightforward to implement.
* In the case that `T>0` we map `:` over the list with axes `t-1` and `y-1`.
* In the case that `T=0` and `Y>1`, we transpose the matrix and call `:` on the transposition with axes `1` and `Y`.
* And finally in the case that `T=0`, `Y=1`, and the matrix has depth greater than 2, we map transposition over the list and call `:` on that with axes `0`, `2`.

```
.N                                        # define :(N, T, Y)
  ?T                                      # if T != 0:
    :RtTtYN                               #   map : over N with additional arguments T-1, Y-1
           ?tY                            # else if Y > 1:
              :CN1Y                       #   :(transpose(N), 1, Y)
                   ?sIssN                 # else if matrix depth is 2
                         s                #   sum of
                          .e   N          #   map lambda k, b over the indices, values of N
                            @bk           #     b[k]
                                          # else
                                 CMN      #   map transposition over N
                                :   T2    #   :(above, T, 2)

```

---
Tags: code-golf, math, array, matrix, linear-algebra
---