-4
\$\begingroup\$

Is this Q too easy to ask, or has it just never been thought of?

Generate a random number, either 0 or 1 using a program

You may use a pre-defined function. The code must be executable. (It can't be just a function that requires more code to execute.) Randomness of the output will be verified by showing that it is not possible for a human/computer today to predict the output of the next execution (unless the exact algorithm is revealed), even when given an infinite set of outputs on previous executions of the code.

I'm looking for the most interesting code (never mind if it's lengthy).

Note: I had initially asked for the shortest code. The answer to that is 2 bytes long. It's O2 in Pyth, according to @Dennis

\$\endgroup\$

closed as primarily opinion-based by Peter Taylor, feersum, Daniel M., Alex A. Nov 1 '15 at 23:42

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 4
    \$\begingroup\$ All challenges require an objective winning criterion. Unless you specify how code length (code golf) and votes (popularity contest) are going to be combined, the challenge doesn't have one and is therefore off topic. \$\endgroup\$ – Dennis Nov 1 '15 at 15:09
  • 1
    \$\begingroup\$ Also, this is trivial in most programming languages, but depends highly on what you mean by random in those where it's an interesting task. You should probably clarify how submissions are tested for randomness. \$\endgroup\$ – Lynn Nov 1 '15 at 15:11
  • \$\begingroup\$ @Dennis Is it okay now? I meant for the shortest code challenge to be only an additional one (since it's easier). \$\endgroup\$ – ghosts_in_the_code Nov 1 '15 at 15:24
  • 11
    \$\begingroup\$ Asking for "interesting solutions" to trivial tasks doesn't usually inspire creativity. While popularity-contests are certainly on topic, you should expect quite a lot of downvotes, as they aren't usually very well received unless the challenge is actually best judged by humans (e.g. image processing). If you just went with a plain code golf, you might get boring answers in common languages with built-ins but very interesting answers in esoteric languages which have to implement their own random number generator. \$\endgroup\$ – Martin Ender Nov 1 '15 at 15:29
  • 1
    \$\begingroup\$ For such a simple and standard task, popularity contest is meaningless. Many languages have an obvious way to do it. You might get answers that do it in a weird way, but most will just use the built-in made for it. For these, there's nothing to judge except the choice of language. There's no point making weird embellishments either for the sake of creativity. \$\endgroup\$ – xnor Nov 1 '15 at 17:59

24 Answers 24

6
\$\begingroup\$

Pyth, 2 bytes

O2

Try it online.

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

Labyrinth, 7 bytes

I think this is also the shortest answer in Labyrinth... and I think it's fairly interesting.

v
)
"!@

Labyrinth does have built-in random behaviour but it's normally very hard to access. The conditions are as follows:

  • The instruction pointer (IP) needs to be on a cell with two neighbours in opposite directions.
  • The IP must not be pointing at either of the neighbours.
  • The value on top of the main stack must be zero.

If all of those conditions are met, the IP will choose a uniformly random direction towards one of the two neighbours.

In larger programs, this is incredibly tricky to setup, because normally there is no way to make the IP move such that it faces a wall if there isn't another neighbour at its back. The only way to set this up is by using the source-manipulation commands <^>v. These cyclically shift a row or a column of the source code. If the shifted row or column is the one the IP is one, the IP will be shifted along without changing its orientation. This way we can move the IP into position.

Now let's look at the code. The IP starts out on the first cell, pointing right. The v shifts the first column down one cell, taking the IP with it:

"
v
)!@

Now the IP points East, has a neighbour North and South, and the main stack still has only zeroes on it, so all conditions are met. What are the options now?

If the IP decides to move South, ) increments the zero on top of the stack to 1 and ! prints it. @ terminates the program.

If the IP decides to move North, " is a no-op. The IP hits a dead end and turns around. Now it hits the v again. So we shift one further:

)
"
v!@

Now the IP is in a corner and follows the path around the bend. ! prints the zero on top of the stack, and @ terminates the program.

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

><>, 5 bytes

lxn;n

><> is a 2D language, and x is "random direction" (up/down/left/right) in ><>. Since ><> is toroidal, up and down do nothing, as this is a one-liner and wrapping around makes us end up in the same spot. Thus, only moving left or right at the x do anything in this program.

The initial l pushes the length of the stack, 0. At the x, moving right makes us print the top of the stack with n, then halt with ;. Otherwise, moving left executes l again, pushing 1 before we wrap around, print and halt.


And for the popcon, we have:

0 >   xxxxx aa*(n;
  ^+1 <<<<<

This is "The Ledge: ><> plays Pokemon version". The instruction pointer needs to get past the row of xs, with falling off the ledge (random up/down) moving us back to the start, incrementing a failure counter. It's a race against time, with the program printing 1 if the IP makes it to the end whilst falling off at most 99 times, else 0.

\$\endgroup\$
5
\$\begingroup\$

AppleScript/osascript, 17 Bytes

AppleScript is really a passive-aggressive teenager. o-o

some item of{1,0}

Or, 18 bytes:

random number of 1

This is kinda the cheaty way to do it. some item will grab a random item of a list. If I wanted a random item of a series, I would use:

random number from 0 to 100

For a random integer in the set [0, 100].

\$\endgroup\$
  • 7
    \$\begingroup\$ I like how lazy AppleScript sounds here. "Eh, some item from that set. Whatever, I don't care." \$\endgroup\$ – Alex A. Nov 1 '15 at 18:39
  • 2
    \$\begingroup\$ "Meh." - Script Editor, 2015 \$\endgroup\$ – Addison Crump Nov 1 '15 at 18:39
  • 1
    \$\begingroup\$ @AlexA. Actually, Script Editor is a grammar nazi. If you put in it's <property>, it'll autocorrect to its property --Grammar Police, where -- is a comment. \$\endgroup\$ – Addison Crump Nov 1 '15 at 20:42
4
\$\begingroup\$

Vitsy

I'm changing my answer to fit the popcon description.

2R(10r68*+DD:::?? WHY WOULD YOU WRITE LIKE THIS?
2R                                                Random float in [0,2).
  (10                                             If its truncated value is 1,
                                                  Push one. Then push 0.
     r                                            Reverse the stack.
      68*+                                        Add 48.
          DD                                      Duplicate, duplicate.
            :::??                                 Clone the stack thrice, rotate
                                                  stack position twice.
                   WH  W U D  U W       K   H     NOPs.
                     Y                            Delete the current stack.
                        O                         Output the top item of the stack
                                                  as a truncated int character.
                          L                       Get the length of the stack.
                            Y                     Delete the current stack.
                             O                    Output again (outputs nothing)
                                 R                Random integer.
                                  I               Get the input length.
                                   T              Tangent of the top item.
                                    E             Push the constant e to the stack.
                                      LI E T IS?   Already described above...

\$\endgroup\$
  • \$\begingroup\$ Clever using the NOPS to form a coherent thought \$\endgroup\$ – Conor O'Brien Nov 1 '15 at 17:22
  • \$\begingroup\$ In Vitsy, anything that's not a command is a NOP. I hadn't used this feature before, so I though... whynaut? @CᴏɴᴏʀO'Bʀɪᴇɴ \$\endgroup\$ – Addison Crump Nov 1 '15 at 17:23
  • \$\begingroup\$ Fascinating! `` \$\endgroup\$ – Conor O'Brien Nov 1 '15 at 17:24
3
\$\begingroup\$

TeaScript, 2 bytes

Using some not-so-new-but-implemented-last-night features, ¡ (inverted exclamation) compiles to (). Because of issues with permalinks and special characters, you have to copy and paste this code into the online interpreter

\$\endgroup\$
3
\$\begingroup\$

Simplex v.0.7, 2 bytes

IX
I  ~~ increment byte
 X ~~ set byte to a random number from 0 to the current byte value

The byte is valued 0 by default; incrementing it by 1 then applying the random function makes it a random value from 0 to 1 inclusive.

\$\endgroup\$
3
\$\begingroup\$

Microscript, 2 bytes

r2

Microscript II, also 2 bytes

2R
\$\endgroup\$
2
\$\begingroup\$

Python 3, 22 bytes

print((hash(id)>>9)&1)

In python 3, the output for the hash function was randomized per run by default.

This was because in older versions, you could make an attack on the dictionary object if you could insert arbitrary objects (such as strings for usernames or integers for uuids). You could exploit the way the dict object was implemented so you could make retrieving objects from the dictionary take much much longer than normal.

Because of this, hash became randomised. I'm exploiting this for the challenge so I don't need to import the random module. I'm doing >>9 because although randomised, during the tests I ran, the last several bits never changed although this bit sometimes did. On my computer, it outputs 0 most of the time but sometimes outputs a 1.

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

CJam, 3 bytes

2mr

Try it here.

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

Befunge, 6 bytes

?1.@.0

The PC starts at the top-left corner, moving right. When it runs into ?, it will either

  • Move up or down, in which case it wraps vertically back to the very same ?
  • Move left, wrapping around and executing 0, . and @: this prints a zero and halts the program
  • Move right, executing 1, ., and @, which prints a one and halts the program.

Works for both Befunge-93 and Befunge-98.

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

Ruby, 8 bytes

p rand 2

Probably the shortest it gets in Ruby.

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

Python 2, 16 bytes

This one is pretty fun:

print id('')/3&1

In CPython, at least, id('') is different every time, because the string literal '' is at a different position in memory each time the interpreter is ran. We can't directly take the least-significant bit, because it's obviously aligned to a valid address. However, dividing by three first works fine.

\$\endgroup\$
  • \$\begingroup\$ My and your answer are pretty much identical. Also posted in same minute. How can we work out who was first? \$\endgroup\$ – Blue Nov 1 '15 at 17:11
1
\$\begingroup\$

Mathematica

Boole[OddQ[ToExpression[StringSplit[ToString[s = SiderealTime[][[1, 3]]], "."][[-1]]]]]

Explanation

SiderealTime[] gives the present sidereal time.

s = SiderealTime[]

time


The code for the above time is revealed by its LongForm.

LongForm[s]

Quantity[MixedRadix[14, 10, 33.3553], MixedRadix["HoursOfRightAscension", "MinutesOfRightAscension", "SecondsOfRightAscension"]]


s[[3,1]]

The element at position {3,1} in the expression is

33.3553


ToString[%] converts this to a string.

"33.3553"


StringSplit["33.3553", "."]

breaks the string at the decimal point.

{"33","3553"}


{"33","3553"}[[-1]]

returns the last element, namely, "3553"


ToExpression["3553"]

converts this to an integer.

3553


OddQ[3553] returns

True

because 3553 is odd.


Boole[True] returns 1 for True.

Boole[False] would have returned 0.

\$\endgroup\$
  • 4
    \$\begingroup\$ Once again, Mathematica saves the day with the awesome power of built-ins...or not. +1 anyway. \$\endgroup\$ – ETHproductions Nov 1 '15 at 16:36
1
\$\begingroup\$

Perl, 28 bytes

my $rand=int(rand(2));
print $rand, "\n";

Golfed version, just in case it changes back again (I'm scoring in the headline by this):

my $a=int(rand(2));print $a;
\$\endgroup\$
  • \$\begingroup\$ You can do say int rand 2 for 14 bytes. You can use say for free because you can run with -E instead of -e on the command line. Try it with perl -E'say int rand 2' \$\endgroup\$ – chilemagic Nov 2 '15 at 16:12
0
\$\begingroup\$

Java, 88 Bytes

class A{public static void main(String[]a){System.out.println((int)(Math.random()*2));}}

Readable version:

class A{
    public static void main(String[]a) {
        System.out.println((int)(Math.random()*2)); // Get a random float from [0, 2) and truncate it to an integer.
    }
}
\$\endgroup\$
0
\$\begingroup\$

GolfScript, 5 bytes

2rand

Basically exactly like the CJam answer, but with a longer keyword.

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

Ruby, who cares bytes

Seems this isn't a code-golf challenge anymore? Here's some multithreading for ya.

[0,1].map{|i|Thread.new{$n=i}}.map{|t|t.join}
p $n
\$\endgroup\$
0
\$\begingroup\$

gs2, 2 bytes

In CP437:

↕%

Hex dump:

12 25

Pushes 2, then calls random, generating a random number between 0 and 1.

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

Perl, 14 bytes

print 0|rand 2

Example:

$ perl -e 'print 0|rand 2'
1
$ perl -e 'print 0|rand 2'
1
$ perl -e 'print 0|rand 2'
0
$
\$\endgroup\$
0
\$\begingroup\$

bash, 19 bytes

echo $(($RANDOM%2))
\$\endgroup\$
  • 1
    \$\begingroup\$ RANDOM needs no leading $ inside ((...)) and $((...)) can be written as $[...]. \$\endgroup\$ – yeti Nov 1 '15 at 17:15
0
\$\begingroup\$

Javascript ES6, 22 bytes

Quite simple.

alert(0|Math.random()+.5)
\$\endgroup\$
0
\$\begingroup\$

PHP "The Lottery"

In Germany we have a very popular lottery called "6 aus 49" ("6 from 49"). You tip 6 numbers out of the range 1 to 49. If you have selected at least 2 numbers that also the "Lottofee" ("Lottery Fairy") has picked, you win.1

The code below has a player against the lottery. If the player loses it will output 0, if the player wins it outputs 1. As the distribution of a lose to win was still 1:5 I changed the rule, that at least one number must be picked by both the player and the lottery for a win. This results in an almost even distribution with slightly more wins.

function pick() {
    $numbers = [];
    for ($i = 0; $i < 6; ++$i) {
        $pick = mt_rand(1, 49);
        while(in_array($pick, $numbers)) {
            $pick = mt_rand(1, 49);
        }
        $numbers[] = $pick;
    }
    return $numbers;
}

$player = pick();
$lottery = pick();

print ( count(array_intersect($player, $lottery)) > 0 ? 1 : 0 ) . "\n";

That's a bit simplified, but the general idea.

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

Lua,   30   18 bytes

This answer is based on the same idea as muddyfish's answer.
In Lua order of elements in a table depends on hash, which is randomized per run.
We simply printing the first key in a table consisting of just '0' and '1':

$ lua -e "print(next{['0']='',['1']=''})"

EDIT:

Another version (length mod 2 of some unpredictably chosen global variable's name):

$ lua -e "print(#next(_G)%2)"
\$\endgroup\$

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