Description: Random generator - Throw dice(s)

Posted on 12.12.2016 | Last modified on 21.12.2016

Short description

This random generator throws one or more dices.

What is randomness?

Randomness is an event for which there is no causal explanation. This means that the result of a random generator may not be predictable or computable. This, however, contradicts the laws of each computer. In other words, a computer can not produce absolutely random numbers without additional peripherals. In this case we call it pseudo-random numbers. In general, you can philosophize about at which point you can actually speak about randomness.

How are "thrown" the dices?

In principle, two different mechanisms are used to generate pseudo-random numbers in this generator.

Random generator 1 for binary string

The first mechanism is used to generate the binary string in the background. On the one hand, this is for better optics and on the other hand it can be ensured by the user, that a new random value has actually been generated. For creating the binary string, the PHP functions mt_rand() and decbin() are used. The first function generates the actual random number and the second is used to convert the decimal number into a binary number. In principle the following algorithm is used:

1
2
$random_string = "";
while(strlen($random_string) < PREFERRED_LENGTH) $random_string .= decbin(mt_rand(NUMBER1, NUMBER2));

Random generator 2 for "throwing dice(s)"

The previous random number generator produces relatively good random numbers, which, however, can further be improved. For throwing the dices, the function random_int() is used, which generates cryptographically secure pseudo-random numbers:

1
2
3
4
5
6
7
8
9
10
// Initialization
for($i = 1; $i <= 6; $i++) $dices[$i] = 0;

// For all dices
for($i = 1; $i <= $number_dices; $i++) {
	
	$number = random_int(1, 6);
	$dices[$number]++;
	
}
Share this post