How to Generate Random Values by Dice Roll in C++

Jay Shaw Feb 02, 2024
  1. Generate Random Numbers by Dice Roll in C++
  2. Generate Random Values Similar to a Dice Roll Using C++
  3. Conclusion
How to Generate Random Values by Dice Roll in C++

Computers cannot guess numbers. Every time a machine generates a random number, it’s either a product of some bitwise operation or a derivative of a numerical factor, i.e., time, sequences.

The issue with using the above methods is that they will produce the same set of results if repeated enough times.

This is why conventional algorithms used to generate random numbers are not recommended for cryptographic practices. The outcomes are easy to predict.

In predicting randomness, rolling dice is a fairly straightforward task. In this article, the reader will learn about randomness in computers and how random results can be fetched from a simple dice roll using C++.

Generate Random Numbers by Dice Roll in C++

A pseudorandom generator is a machine that creates numbers that seem to be random. Conversely, they are entirely predictable.

This is because traditional random number generators employ the use of a seed. A seed, in simple terms, is an injective function that is reliant on a time or a numerical component.

For example, the outcomes produced for a given seed x(0) by repeatedly applying an injective function on x(0), termed f(x0), so that fn(x0) differs from fn-1(x0) or fn+1(x0), where fn represents the function structure n times.

In other words, f(x) contains large leaps that are practically unrelated to the prior ones.

Seed Using Time to Create Random Number for Dice Roll in C++

In most cases, the seeds generated are dependent on the time factor. That means the injective function factors the current second in the clock.

Let’s look at an example to understand it in a better way.

unsigned main_seed;

main_seed = time(0);

srand(main_seed);

Here, an unsigned variable main_seed is initialized; this variable is used to store the current time. srand() is a C++ function that generates a result from the seed.

Once the seed is generated, the rand() function can be used as a seed to generate random values using a linear equation.

Using time factor for fetching distinctive seeds might seem a good practice unless modern CPUs are involved because they deal with processes in nanoseconds, which disrupts the whole function in terms of randomness.

In most cases, the seeds generated are dependent on the time factor. That means the injective function factors the current second in the clock.

Because the clock is not as quick as one might think, if srand(time) is used numerous times in a second, the same seed gets obtained multiple times. As a consequence, the produced set of random numbers will be similar.

And this might be a (significant) problem, especially in block cipher programs. In the latter case, people buy a decent number of generators built on real-time physical adjectives such as temperature variance in atmospheric data, etc., or, lately, on measuring quantum bits, e.g., on the factor of how polarized photons are superpositioned.

Seed Using Arbitrary Numbers to Create Random Number for Dice Roll in C++

The below example demonstrates a pseudo number generator using numbers.

static unsigned long int rand_num = 2;

int rand(void)  // The ceiling limit is kept at 32767
{
  rand_num = rand_num * 113546545 + 12345;
  return (unsigned int)(rand_num / 65536) % 32768;
}

void srand(unsigned int main_seed)  // seed is stored inside variable main_seed
{
  rand_num = main_seed;
}

An unsigned int variable rand_num is initialized with the value 2. There are two methods in the above program - rand and srand.

The rand method concatenates a new number to the initialized value. As the ceiling limit for the seed is set, the mod of rand and the ceiling limit will return a number lower than the ceiling limit.

The final result returned from this method is typecast into an unsigned int.

The method srand() passes the value from rand_num to the seed variable main_seed.

Drawbacks of Using the Above Methods

As it can be seen, executing srand(time(0)) or taking arbitrary values for seed always returns fresh numbers on rand(), which are dependent on the seed. But after a few million, the numbers get repeated.

The seed controls which random numbers are created in order, i.e., srand(1) will almost always produce the same value on the first call to rand(), the same number on the second call to rand(), and so on.

In other words, the output is always the same random number if the same seed is re-seeded before each rand() call. So seeding several times with time(0) in a single second will result in all the random numbers being the same after re-seeding.

It must repeat after a few cycles, but the srand argument defines the pattern. C++ rand is unsuitable for encryption since knowing the seed helps a hacker estimate the next number.

Generate Random Values Similar to a Dice Roll Using C++

This program uses a time-generated seed to produce random numbers in the range of 1 to 6.

Import Packages

Three import packages are needed in this program:

  1. iostream
  2. cstdlib - for time function and rand operations
  3. time - header package for time functions

iostream is imported for input-output operations in the program. The other package, cstdlib, is used for basic control operations in C++ programs.

The third package is the time package that will be used in creating the seed for the program.

Generate Values as per the Die Roll In C++

A die has 6 individual values. The role of the program must be to generate a random natural number inside the range, which may repeat in subsequent die rolls, but the overall outcome must look purely random.

Three variables are initialized to find the outcome. Variables floor and ceiling store the lowest and highest values of the die, and the variable outcome is used to find the random number.

int outcome;
int l_limit = 1;
int h_limit = 6;

The final value is generated using the rand() function, limiting the outcome inside the upper and lower range.

outcome = rand() % (max - min + 1) + min;

Finally, the variable roll is returned.

int outcome;
int l_limit = 1;  // floor or lower limit of a die
int h_limit = 6;  // ceiling or higher limit of a die

outcome = rand() % (h_limit - l_limit + 1) + l_limit;

return outcome;

Generate a Seed Using Time and Display the Results

The program takes the current time inside the srand() function and passes it to the rand() function. The application uses the rand() function from the method Droll() to find natural numbers inside the stipulated limits.

srand(time(0));

After the seed has been produced, the Droll() method must be called, and the outcome must be printed.

Conventionally, three die rolls are always considered a complete set. This technique is repeated three times to verify for randomness.

We will need to put the Droll() method inside a for loop and call three times inside the print statement. The final result is a 3X3 matrix of pseudo-random numbers generated from a die roll.

for (int i = 0; i < 3; i++) {
  std::cout << Droll() << " ";
  std::cout << Droll() << " ";
  std::cout << Droll() << std::endl;
}

Let’s put everything together inside the program and view the results.

#include <cstdlib>
#include <iostream>

#include "time.h"

int Droll() {
  int outcome;
  int l_limit = 1;  // floor or lower limit of a die
  int h_limit = 6;  // ceiling or higher limit of a die

  outcome = rand() % (h_limit - l_limit + 1) + l_limit;

  return outcome;
}

int main() {
  srand(time(0));
  for (int i = 0; i < 3; i++) {
    std::cout << Droll() << " ";
    std::cout << Droll() << " ";
    std::cout << Droll() << std::endl;
  }
}

Output:

3 1 2
6 1 3
4 5 4

--------------------------------
Process exited after 0.00784 seconds with return value 0
Press any key to continue . . .

Conclusion

This article explained the basics of pseudo number generators. The readers have seen the different methods to generate a random number and their advantages and drawbacks.

A C++ program is given to make the concepts crystal clear over how random numbers get generated inside the range and how a dice roll can be mimicked using a computer program.

Related Article - C++ Random