How can I randomise the output of a redstone circuit?

I have 5 buttons and only one of these can be correct, all others must be false.

These 5 outputs will go into 2 outputs, in between there needs to be a circuit which changes which single button out of the 5 will go down the "correct" output of the final 2. The 4 remaining buttons must go to the second of the final 2 outputs.

Both final outputs must give out a true signal for a brief period the same as a button on its own would produce.

There should also be a way of activating the circuit.

Not sure if that is explained well enough so I have made a basic diagram of what I need.

Diagram of redstone circuit

The diagram shows how I need the signal to be split. However in between the buttons and the final two wires there needs to be a circuit (marked by the grey box). This circuit changes the single button connected to the left wire. The right input should start the circuit and randomise the 5 buttons.

There are no limits to size, amount of materials used or method used.

This question is similar to the one asking about random numbers in Minecraft commands, but I am specifically working with Redstone circuitry - the commands solutions do not apply here


Solution 1:

Since there is no answer I will show how to make a random unit:

If you are not ready to have your mind blown go to conclusion at the end.

Take a 3-clock unit and set an output somewhere, now since this is only 3-clock it's gonna burn at RANDOM place so the output will be random. Like this: enter image description here

Now you probably don't want it to change so much but only when it stopped, well.. idk if anyone used it(probably used), anyway I've made it my self, I call it "signal cuter" the point is to split the signal into 2 signals: first contain odd number of "not gates" and the second even, and then merge them into "or gate", the result is: when a signal is sent, it's gonna stay as the output until the second path will cut the signal and that way no matter for how long you set the input to "on", the output gonna be "on" only for length(second path) - length(first path) "ticks".

enter image description here

in this example, all signals that are more then 3 ticks length are shorted to 3 ticks long. On same property you can make a "signal protector" also made by me :), it's not passing signals less than X long all the difference is that both paths first and second need to be odd length and the X is equal to length(second path) - length(first path), but the signal become shorter then the original signal length. Example:

enter image description here

FINALLY the conclusion: so now you can take the a 3-clock and to chain it with the "signal protector" with X=2 and THIS WILL BE STABLE!! It won't throw junk until the 3-clock burned and the result is stable, the next random will be generated after the next 3-clock burn, if you want to make it faster just make many units of that.

THE RESULT:

enter image description here

It's still throw junk in "Redstone Simulator" but in "Minecraft" this works great! Please if you're passing on this technique, leave the names "Signal Cutter" and "Signal Protector".

Solution 2:

This question appears to be the main attractor for any and all questions involving creating a source of randomness in Minecraft, but most of the solutions are spread over related/duplicate questions. This answer compiles together the information in a single place to provide a more complete solution to the problem.

This post is very likely incomplete - Feel free to edit this post with any additional information that provide more insights or alternative methods.


With the explanations out of the way: Let's list the other solutions to the question, and why and how they are applicable.

I've also added commentary in the list which is important to any implementer, any caveats to the solutions not already provided in the answers themselves.

Existing hacks

These mostly use an existing 'source' or construct their own 'base' of randomness.

Some notation: S is the variable denoting the number of states in the output: I.e. the size of the die rolled. N is a variable scaling factor by which the generator can be modified; N >= 1 and it is a whole number. The easiest values for S to work with is powers of two for the purposes of converting to any number. Of course, if all numbers are available that's better still; yet the most time-efficient solutions tend to be binary.

  • Timer source

https://gaming.stackexchange.com/a/18617

An addendum to the answer by @cyclops. Required to implement it (contains ways of building some subcircuits the answer refers to). Answer contains detailed explanations and a working redstone circuit.

A clock isn't a very good source of randomness: go watch pokemon red noglitch speedruns to find out why: turns out humans can get quite good at pressing buttons on a certain frame and reverse-engineering RNG systems. These may be too simple to utilize for the average gamer who will beat your system using dexterity.

https://gaming.stackexchange.com/a/215506

Provides an example construction of a timer-based random number generator. Unlike many of the examples and videos linked this is a good version for a beginner: it's a simple, flat structure that does not use complicated redstone compacting tricks and different types of powered blocks like most of the other explicit solutions; it's 'ungolfed', so to speak. That does mean it tends to be space-hungry.

https://gaming.stackexchange.com/a/126893

Adds notion of a memory cell to the canon clock-based solution (though does not provide a concrete implementation).

https://gaming.stackexchange.com/a/188261

Another way of constructing a timer-based random circuit. Provides a concrete implementation.

https://gaming.stackexchange.com/a/31629

Provides a description of a timer-based random circuit. Does not provide a concrete implementation.

https://gaming.stackexchange.com/a/278591/148546

Provides a way command blocks can be used to store the output of a timer-based circuit.

  • Spawner source

https://gaming.stackexchange.com/a/203924

Adds a new type of solution: Spawn a monster within a radius, use a bunch of pressure plates to measure where it spawned. The monster would trigger a random one. Not a perfect solution:

  • Radius spawn function isn't uniformly distributed.
  • Causes noise.
  • Can glitch if spawn is triggered but kill is not.
  • Outputs S=(2N + 1)^2 values (hard to work with)

https://gaming.stackexchange.com/a/126863 and https://gaming.stackexchange.com/a/141492

The answers link this video as an example build.

  • Dispenser source

Utilises a dispenser to forward the internal RNG of the dispenser. Complicated setup, slow, involves items, but may work. Answer does not provide a concrete implementation.

Does not provide a uniformly distributed output. See this reddit post where the user tested such a setup.

The minecraft wiki recommends certain workarounds for this and has compact, tested configurations for some RNG devices.

https://gaming.stackexchange.com/a/284279/148546

Utilizes repetition and varying types of items, also uses some of the other methods, though not as the source, merely as part of the device. It is a bit of a rube goldberg solution, and will not be distributed evenly: even ignoring the dispenser bugs, there is a problem that the various spots are distributed in a complicated pattern based on the geometric distribution. The minecart can loop around the track before stopping, applying a modulo operation on top, layering a discrete geometric distribution onto itself recursively. Applying the math; specifically, with S=N outputs:

Probability distribution equation for the roulette

Or, more concrete, setting N=5, here's the distribution:

k P
1 .297
2 .238
3 .190
4 .152
5 .122

So this solution does not quite give an equal result even before factoring in the dispenser bug. It also has a limit of 1 <= r <= 9 for the exponent due to there being at most 9 slots. It does have S=r^N when you run multiple copies.

https://gaming.stackexchange.com/a/371339

This answer utilises a dispenser in a repeat fashion (much like the previous) to create russian roulette with 6 chambers, one bullet by using 5 single stacks of 1 stackable, and one unstackable to create the same increase in chance of getting shot (i.e. the 'taking random marbles out of a bag of 1 red, 5 blue'). If this is the specific game you want, such a direct solution is preferrable to programming in the increased chance of pulling the bullet with every pull using a generic RNG.

It also uses another property of a dispenser: depending on whether it contains a non-stackable item it emits a different redstone signal, to get a much simpler construction. This construction is only described; the answer contains no concrete implementation.

https://gaming.stackexchange.com/a/229716

A refinement of the post above, this uses a set of such dispensers in series. By using a series of dispensers, the bug above is circumvented to some extent. I cannot find a dispenser test online with just two outputs, so this would need to be tested as well.

Remaining TODO: test whether the above works with two items in the dispenser. Iff it does, then this is a very good base for a solution. Unfortunately, the solution is incomplete. Again a concrete implementation is missing. In addition, only powers-of-two are available.

The three videos linked treat other methods, in order (consult the relevant section for more info):

  1. An example build with any S = N^2 output.
  2. A timer source generator with S = 2N values. (see the explanation for timer source above)
  3. Multiple solutions: 3.1 Dispenser based (this section)
    3.2 Spawner based (see section above).
    3.3 Command block source (see section below).

The video version 3.2 of the spawner base solves the 'kill' problem, but introduces a new problem by moving a monster instead. If your map involves a /killall type command (which is fairly common to get rid of random mobs) then the RNG stops working.

  • Piston source

https://gaming.stackexchange.com/a/296219

This is actually a very intriguing solution. Unfortunately the answer is very short, does not provide a concrete implementation, and does not provide the details. In essence, it exploits this minecraft bug. Also see Minecraft piston pushing against each other. Caveats:

  1. The Machine is likely to produce the same output if setup the same: it's unintended randomness involving internal Java implementations.
  2. If the bug is ever fixed (which it very well might) the solution will stop 'working'.
  3. Highly likely to fail randomness tests in complicated ways: HashMaps are designed for memory efficiency, not randomness.
  • Command block source

https://gaming.stackexchange.com/a/320840

Solution involves using the @r tag within a command within a command block. Caveat is that only certain commands support using the @r tag directly, and the answer does not provide a way to implement such a specific command to work in an arbitrary machine: produce a random output of 0 or 1. Instead it directly implements a random teleporter, which is one use of a random generator (the one the asker wanted), but not every use in general.

Works with potentially any S=N, but may need testing; haven't found posts on the reliability of @r, but I presume it's possibly the best solution for most cases, as it likely directly calls the Random() class; in other words, a proper PRNG, part of the Java language that's battle-tested and viable for nearly all non-crypto use cases.

The video linked in a previous answer does do so more generally using command blocks. (See point 3.3 in the section about Dispenser source).It is a very interesting solution as it is a refinement of the command block source type solution removing its main drawback; involving a command of this type (two-lined for readability):

/execute @r[type=ArmorStand,name=RandomGenerator001] ~ ~ ~ \
/summon FallingSand ~ ~ ~ {Tile:sand,Block:sand,Time:1,DropItem:0}

Using stands with these attributes:

{CustomName:"RandomGenerator001",CustomNameVisible:1,NoGravity:1}

With a bunch of floating ArmorStands named RandomGenerator001 dropping sand tiles on pressure plates that automatically disappear. By using S=N=8 (probably most efficient) you can generate random bytes to do very large random numbers: e.g. if you wanted output from 0 to 1,000,000 you would obviously use 3 bytes and drop some bits; reroll between 1,000,000 < N < 1,048,576.

https://gaming.stackexchange.com/a/285355/148546

Describes an alternate equivalent way of utilizing the @r tag by spawning and despawning redstone blocks. Provies detailed command block code but no detailed diagrams of how to construct the device (only difficult to decipher descriptions).

Melon Source

A rather unique and very slow approach to the problem, the answer to Do Melons prefer to grow in certain directions? provides us with another solution: Melon blocks drop melons in a random direction using again a good PRNG. Melons conduct redstone electricity, so by waiting for a melon to spawn (then removing it with a command block) it can be used to generate a random number sequence. Here, S = 4^N; generating a byte at a time with four such constructions applying some quadroolean (meloonian?) algebra.

What to do with bytes

Some of the contraptions linked to above can only produce random numbers in some power of two.

So let's say we have some contraption that produces random bits, nybbles, or bytes. But what if we want some other output? What if our random number should range from 1 to 18? The correct answer is to use encoding and decoding.

What if our target is a d6? how-to-convert-random-bytes-into-blocks-of-numbers-without-weakening-entropy provides some solutions, but concrete redstone circuitry to discard outputs that are too high and try again is not provided by this answer: it's only theoretical. But it does provide insight in how to do it: simply discarding out-of-range inputs preserves entropy.

Practically speaking, How to build a two bit binary to decimal decoder using Redstone? can help you decode output. The accepted answer can map any input to any output; it's easily reprogrammable and adaptable if you have the desired truth table worked out. So if we wanted an output from 0-5, you would use 3 inputs, discard 101, 110. 111 (or connect these outputs to a try-again toggle), and map as follows:

n x
1 000
2 001
3 010
4 011
5 100

Simply by looking up the row, we'd know that d5 = b1 & !b2 & !b3; it functions as a truth table for the desired decoder.

Larger numbers

When dealing with much larger numbers, such a decoder would become cumbersomely large; too large for the game to handle. The trick is to use a binary comparator; do your filtering in binary, then decode the result if desired. See this question on how to build a 4-bit comparator (currently an open problem on this site, though videos can be found, but they're usually poorly explained beyond 'place blocks like this'). These can be cascaded to make larger and larger comparators (4, 8, 12, 16, ...). See this resource on how to connect them up.

Explanations

This question; How can I randomise the output of a redstone circuit?, asked in 2011, has many duplicates or near-duplicates. They have been closed mostly recently (last 2 years). Several of these duplicates have themselves duplicates, closed in a previous round of duplicate hunting, which have themselves duplicates...

recursion

Most of these 'duplicate' questions have good, quality answers. In fact, the old answer to the question in fact partly resides in one of the duplicates. In addition, the old answer was for a very early version of the game: multiple newer solutions exist that are effectively a better answer.

Most of the "solutions" are not really complete solutions. I for one would certainly not trust any certificate file generated with those minecraft RNGs. People build all sorts of games in minecraft. A random number generator is an important base concept in programming. Unfortunately minecraft does not provide direct access to proper RNG without mods/plugins; most of the hacks suggested as solutions don't meet some or even all of the randomness tests required for whatever thing the reader has in mind. There's some nuanced math going on here, and some of your problems are going to need more (or less) strict definitions of randomness.

For some examples: A card game like blackjack, would need to have a well-behaved shuffle without any predictability (so that knowing that e.g. the discard pile is 'top-heavy' does not impact the new draws). Any dice would need evenness (all numbers equal probability). Generated passcodes need resistance against guessing (Crypto-Secure). Etc etc. Here's a Venn diagram sketch of what I mean:

Random generator types

So this question actually has multiple answers: which tests you need to beat depend on what you want to do with your random numbers. So multiple types of solutions can be applicable. Whence, most of the well-written answers add their own value. So, compiling the answers in a single place (instead of having to dig around in multiple layers of duplicates) is also valuable.

It's not all bad news though: Minecraft has in it basically a somewhat ideosyncratic and buggy simulation of electricity, and thus electric logic circuits can be modelled to some extent. Computers are basically electronic logic circuits, so in theory you can build any PRNG: Minecraft is turing-complete. In practice, these will end up too slow to be workable for the solution you have intended (try programming say MT19937 in redstone), and finding some leaky abstraction (through which minecraft exposes some well-programmed PRNG from the programming language directly) is the preferred method of tackling this pervasive problem.

Solution 3:

You can make a random number generator with a cactus and pressure plates, you grow the cactus on the center block, and stick pressure plates all around, you then place a block in such a way that whenever the cactus grows it drops a block (this block will be thrown in a random direction), activating one of the pressure plates (wood plates only).

Solution 4:

First, this is a really involved question. :) So I decided to split my answer into two parts, where the second part is a separate Q/A, involving how to activate a random wire.

This part of the Answer, takes that random wire (1 of 5), and multiplexes it with 5 buttons, to direct 1 of the 5 buttons to a valid-output circuit, and the other 4/5 to an invalid-output circuit.

Due to the diagram's complexity, I'm only showing 3 buttons, not 5 - however, extending it to 5 buttons is very straightforward, and should be clear from the diagram.

Top-level circuit diagram

top-level diagram

The 5-Wires box is from the other Question. Basically there are 5 wires (gosh), exactly one of which will be active at any time, with the active wire changing each time a button is pressed. The wires are connected to a 222 circuit, which takes two inputs - a wire, and a button. The 222 circuit has two outputs, connected to two different 5-input OR circuits.

If the wire to a given 222 circuit is active, and the button is also pressed, it will send a positive signal down the red wire, to the valid circuit. The signal will last as long as a button stays pressed, roughly half a second I think. If the wire is inactive and the button is pressed, the 222 circuit will send a positive signal down the green wire to the invalid circuit. In all other cases, there is no signal sent down any wire.

222 Circuit Diagram

222 circuit diagram

Notes

I have tested the individual components in isolation. The 222 circuit works fine, the 5-clock and 333-circuit in the other part, work fine - but I haven't wired up an entire test circuit (not even 3 buttons), because it's really freaking big. However, as far as I can tell, it should work - there are no parts that require extremely precise timing, I turned all the corners on Redstone wiring as needed to avoid glitches, and I don't see any section that would be affected by the SW rule.

I also don't have Baezon's MCE, since it uses Java 6 (I have JRE 5). It might be easier to enter and test in a simulator than doing it by hand, which I was. :) If it doesn't work, let me know what part broke.

The entire circuit is fairly complex, with a lot of wires crossing, but I don't see how you can avoid that. When you're connecting 5 wires to 5 buttons, and directing each result to two other circuits - that's a lot of cross-overs.

The 222 circuit is fairly mundane, I claim no originality - the only reason I gave it a name, is I had to give it some label in the diagram for clarity. :)

Solution 5:

This is a work-in-progress, I plan on adding more updates as I fiddle with stuff, for now I just want to get the conceptual stuff down:

Inputs:

B1 - Button 1
B2 - Button 2
B3 - Button 3
B4 - Button 4
B5 - Button 5
R  - Randomize

Outputs:

V  - Valid, 1 indicates the currently valid button is pressed
I  - Invalid, 1 indicates one or more of the currently invalid buttons are pressed

My current thoughts on this for pseudo-random output are to set up a chain of 4 T flip-flops to a toggleable clock generator. 4T flip-flops create a 4 nybble of data, which holds 16 values (0-15, or whatever obligatory counting scheme you may be using).

16 also happens to be almost divisible by 5, giving you only one extra state, which you can pipe to one of the buttons giving it a slightly heavier weight.

The clock generator should be on only while R is on, and R will ideally be a pressure-plate, so that variable durations may be used. This has the added benefit that the clock generator will not be on constantly, and that a shorter clock-cycle may be used if burnout doesn't happen quickly.

The output of the T flip flops can ANDed with the input from B[1-5] to produce the desired output. I will go into more details later.