Basics of rand() in C++ & its Application.

 Basics of rand()

The rand() function in C++ generated a random value in the 'int' acceptable values. This can be used in multiple cases that helps optimize our code for a better result.

Let us start by learning the basic syntax and how we can manipulate the rand() function to generate a value which we would prefer to see more often.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    //syntax of rand() function
        cout<<rand()<<endl;
        
    //max value of rand() function
        cout<<RAND_MAX<<endl;
        
    //trends with 'int' data type
        cout<<INT_MAX<<endl;
        
    //controlling rand() values
    
        //between 0-9 (inclusive)
        cout<<rand()%10<<endl;
        
        //between 0-99 (inclusive)
        cout<<rand()%100<<endl;
        
    //generate at max 100 values
    //each value being at max 10000
    cout<<endl;
    int n=rand()%100;
    for(int i=0;i<n;i++)
    {
        cout<<rand()%10000<<endl;
    }
}

Now, the application of rand() begin from testing to optimizing to fault tolerance and exception handling.

We can generate a function which would give us test cases for our code. Then we can run it and see of we get a desired output. If we get hit with some error, we will then know for which test cases our code gives this issue.

Let us see this from a bank's perspective. We have 3 variables, exist, deposit and withdraw. Obviously for any test case

if 

    exist + deposit < withdraw

then it should throw an error.

Here is a code which is explained in the shorts.

#include<bits/stdc++.h>
using namespace std;

int generate(int exist,int deposit,int withdraw)
{
    //making test cases
    if(exist==-1)
    {
        exist=rand();
        return exist;
    }
    
    else if(deposit==-1)
    {
        deposit=rand();
        return deposit;
    }
    
    else
    {
        withdraw=rand();
        return withdraw;
    }
}

int condition_checker(int exist,int deposit,int withdraw)
{
    //you can withdraw from new exist value
    exist+=deposit;
    
    //failed condition
    if(exist<withdraw)
        cout<<"'withdraw' too big"<<endl;
    
    else
        cout<<exist-withdraw<<endl;\
        
    return 0;
}

int bank_return()
{
    //the values initialised for condition passing
    int exist=-1, deposit=-1, withdraw=-1, n=0;
    
    //only if n between 1000 & 10000
    //the loop will be exited
    while(n<1000)
    {
        n=rand()%10000;
    }
    
    //generate test values for variables 'n' times
    for(int i=0;i<n;i++)
    {
        exist = generate(exist,0,0);
        deposit = generate(0,deposit,0);
        withdraw = generate(0,0,withdraw);
        
        //to see how the tested values perform
        condition_checker(exist,deposit,withdraw);
    }
    return 0;
}

int main()
{
    //magic area
    bank_return();
}

Here is a sample output.




Comments