Random Number Generation in C++


Code:

//

//  main.cpp

//  VaultBox

//

//  Created by Devharsh Trivedi on 3/11/21.

//


#include <iostream>

#include <iomanip>

#include <string>

#include <map>

#include <random>

#include <cmath>

#include <vector>


int main(int argc, const char * argv[]) {

    std::random_device ranDev;

    unsigned int num_ranDev = ranDev();

    std::cout << num_ranDev << std::endl;

    std::mt19937 mtGen(num_ranDev);

    std::vector<unsigned long> indexes(10);

    

    iota(indexes.begin(), indexes.end(), 0);

    for(int i=0; i<10; i++) {

        std::cout << indexes[i] << "\t";

    }

    std::cout << std::endl;

    

    shuffle(indexes.begin(), indexes.end(), std::default_random_engine(num_ranDev));

    for(int i=0; i<10; i++) {

        std::cout << indexes[i] << "\t";

    }

    std::cout << std::endl;

    

    iota(indexes.begin(), indexes.end(), 0);

    for(int i=0; i<10; i++) {

        std::cout << indexes[i] << "\t";

    }

    std::cout << std::endl;

    

    shuffle(indexes.begin(), indexes.end(), std::default_random_engine(num_ranDev));

    for(int i=0; i<10; i++) {

        std::cout << indexes[i] << "\t";

    }

    std::cout << std::endl;

    

    iota(indexes.begin(), indexes.end(), 0);

    for(int i=0; i<10; i++) {

        std::cout << indexes[i] << "\t";

    }

    std::cout << std::endl;

    

    shuffle(indexes.begin(), indexes.end(), mtGen);

    for(int i=0; i<10; i++) {

        std::cout << indexes[i] << "\t";

    }

    std::cout << std::endl;

    

    iota(indexes.begin(), indexes.end(), 0);

    for(int i=0; i<10; i++) {

        std::cout << indexes[i] << "\t";

    }

    std::cout << std::endl;

    

    shuffle(indexes.begin(), indexes.end(), mtGen);

    for(int i=0; i<10; i++) {

        std::cout << indexes[i] << "\t";

    }

    std::cout << std::endl;

    

    return 0;

}


Output:

4061520885

0 1 2 3 4 5 6 7 8 9

8 6 4 0 5 2 3 7 9 1

0 1 2 3 4 5 6 7 8 9

8 6 4 0 5 2 3 7 9 1

0 1 2 3 4 5 6 7 8 9

2 4 0 5 3 1 9 7 6 8

0 1 2 3 4 5 6 7 8 9

6 7 0 5 1 2 4 9 3 8

Program ended with exit code: 0

This example generates random numbers in modern C++ using the facilities instead of the older rand function. It seeds a generator from std::random_device and draws values through a distribution.

This approach gives better quality and more control than rand, letting you choose the engine and the distribution. For security sensitive work, use a cryptographic generator rather than a general purpose one.

Comments

Popular posts from this blog

[Solved] Error: No such keg: /usr/local/Cellar/gcc

[How To] Unfollow Non-followers on Instagram