Search⌘ K

Random Function

Explore how to create two overloaded random functions in C++. Understand the Linear Congruential Generator algorithm used for producing pseudo-random numbers, and implement these functions to generate both integer and ranged random values. This lesson provides insights into function overloading and random number generation techniques.

We'll cover the following...

Problem

Write a program that provides two overloaded random( ) functions. The first one generates an integer random number, whereas the second generates a random number that lies within the range passed to the random( ) function.

Coding solution

Here is a solution to the problem above.

C++
// Generation of random numbers using overloaded functions
#include <iostream>
int random ( int ) ;
int random ( int, int ) ;
int main( )
{
int i, n ;
std::cout << "Random numbers between 1 to 100: \n";
for ( i = 0 ; i <= 9 ; i++ )
{
n = random ( 100 ) ;
std::cout << n << "\n" ;
}
std::cout << "Random numbers between 100 to 500: \n";
for ( i = 0 ; i <= 9 ; i++ )
{
n = random ( 100, 500 ) ;
std::cout << n << "\n" ;
}
}
int random ( int max )
{
static int xn = time ( NULL ) % max ;
static int cons = time ( NULL ) % 100 ;
static int mult = time ( NULL ) % 120 ;
int xnplus1, temp ;
xnplus1 = ( mult * xn + cons ) % max ;
temp = xnplus1 ;
xn = xnplus1 ;
return ( temp ) ;
}
int random ( int min, int max )
{
int range ;
range = max - min ;
static int xn = time ( NULL ) % range ;
static int cons = time ( NULL ) % 100 ;
static int mult = time ( NULL ) % 120 ;
int xnplus1, temp ;
xnplus1 = ( mult * xn + cons ) % max ;
temp = min + xnplus1 ;
xn = xnplus1 ;
return ( temp ) ;
}

Explanation

The program uses a Linear Congruential Generator (LCG) algorithm that yields a sequence of pseudo-random numbers calculated with a discontinuous piecewise linear equation. The generator is defined by the recurrence relation:

Xn+1=(aXn+c)mod(m){X_{n+1} = ( a * X_{n} + c ) mod (m)} ...