Generate 0 or 1

-4

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

ghosts_in_the_code

Posted 2015-11-01T15:06:03.600

Reputation: 2 907

Question was closed 2015-11-01T23:42:17.103

4All 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. – Dennis – 2015-11-01T15:09:03.363

1Also, 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. – Lynn – 2015-11-01T15:11:37.903

@Dennis Is it okay now? I meant for the shortest code challenge to be only an additional one (since it's easier). – ghosts_in_the_code – 2015-11-01T15:24:11.753

11Asking 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. – Martin Ender – 2015-11-01T15:29:24.547

@MartinBüttner There can be interesting answers such as '#@>#0?1@' in Befunge. Are you going to reopen the Q? – ghosts_in_the_code – 2015-11-01T15:38:12.470

@ghosts_in_the_code I reopened it 8 minutes ago. My point is that you'll still get interesting answers exactly like the one you've mentioned if you make it a code golf. – Martin Ender – 2015-11-01T15:41:29.010

1For 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. – xnor – 2015-11-01T17:59:17.503

The question as specified is impossible without custom hardware by a simple counting argument. – Peter Taylor – 2015-11-01T19:17:22.730

+(Bool.pick)​ – Brad Gilbert b2gills – 2015-11-02T18:03:18.143

for determining how random the function is, I would recommend simply running things many times and counting the results. Since I assume you want uniform randomness, you'd be looking for 50/50. – Liam – 2015-11-02T21:49:09.833

Answers

6

Pyth, 2 bytes

O2

Try it online.

Dennis

Posted 2015-11-01T15:06:03.600

Reputation: 196 637

6

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.

Martin Ender

Posted 2015-11-01T15:06:03.600

Reputation: 184 808

6

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

Sp3000

Posted 2015-11-01T15:06:03.600

Reputation: 58 729

5

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

Addison Crump

Posted 2015-11-01T15:06:03.600

Reputation: 10 763

7I like how lazy AppleScript sounds here. "Eh, some item from that set. Whatever, I don't care." – Alex A. – 2015-11-01T18:39:14.253

2"Meh." - Script Editor, 2015 – Addison Crump – 2015-11-01T18:39:54.353

1@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. – Addison Crump – 2015-11-01T20:42:45.173

4

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

Addison Crump

Posted 2015-11-01T15:06:03.600

Reputation: 10 763

Clever using the NOPS to form a coherent thought – Conor O'Brien – 2015-11-01T17:22:19.753

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ʀɪᴇɴ – Addison Crump – 2015-11-01T17:23:03.070

Fascinating! `` – Conor O'Brien – 2015-11-01T17:24:16.067

3

Microscript, 2 bytes

r2

Microscript II, also 2 bytes

2R

SuperJedi224

Posted 2015-11-01T15:06:03.600

Reputation: 11 342

3

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

Downgoat

Posted 2015-11-01T15:06:03.600

Reputation: 27 116

3

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.

Conor O'Brien

Posted 2015-11-01T15:06:03.600

Reputation: 36 228

2

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.

Blue

Posted 2015-11-01T15:06:03.600

Reputation: 26 661

1

CJam, 3 bytes

2mr

Try it here.

Lynn

Posted 2015-11-01T15:06:03.600

Reputation: 55 648

1

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.

Lynn

Posted 2015-11-01T15:06:03.600

Reputation: 55 648

1

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;

user46470

Posted 2015-11-01T15:06:03.600

Reputation:

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' – hmatt1 – 2015-11-02T16:12:14.600

1

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.

DavidC

Posted 2015-11-01T15:06:03.600

Reputation: 24 524

4Once again, Mathematica saves the day with the awesome power of built-ins...or not. +1 anyway. – ETHproductions – 2015-11-01T16:36:42.107

1

Ruby, 8 bytes

p rand 2

Probably the shortest it gets in Ruby.

Lynn

Posted 2015-11-01T15:06:03.600

Reputation: 55 648

1

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.

Lynn

Posted 2015-11-01T15:06:03.600

Reputation: 55 648

My and your answer are pretty much identical. Also posted in same minute. How can we work out who was first? – Blue – 2015-11-01T17:11:52.237

0

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

Addison Crump

Posted 2015-11-01T15:06:03.600

Reputation: 10 763

0

GolfScript, 5 bytes

2rand

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

Lynn

Posted 2015-11-01T15:06:03.600

Reputation: 55 648

0

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

daniero

Posted 2015-11-01T15:06:03.600

Reputation: 17 193

0

gs2, 2 bytes

In CP437:

↕%

Hex dump:

12 25

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

Lynn

Posted 2015-11-01T15:06:03.600

Reputation: 55 648

0

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
$

steve

Posted 2015-11-01T15:06:03.600

Reputation: 2 276

0

bash, 19 bytes

echo $(($RANDOM%2))

steve

Posted 2015-11-01T15:06:03.600

Reputation: 2 276

1RANDOM needs no leading $ inside ((...)) and $((...)) can be written as $[...]. – None – 2015-11-01T17:15:48.723

0

Javascript ES6, 22 bytes

Quite simple.

alert(0|Math.random()+.5)

Mama Fun Roll

Posted 2015-11-01T15:06:03.600

Reputation: 7 234

0

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.

insertusernamehere

Posted 2015-11-01T15:06:03.600

Reputation: 4 551

0

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

Egor Skriptunoff

Posted 2015-11-01T15:06:03.600

Reputation: 688