How to use the clock as a random generator seed in C++

2 Answers

0 votes
#include <iostream>
#include <random> // mt19937
#include <chrono>

int main() {
    // Use a high-resolution clock to get a more precise seed
    unsigned seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();

    // Initialize the random number generator with the seed
    std::mt19937 generator(seed);

    // Define a distribution range
    std::uniform_int_distribution<int> distribution(1, 100);

    // Generate a random number
    int random_number = distribution(generator);

    std::cout << "Random number: " << random_number << std::endl;
}



/*
run:

Random number: 15

*/

 



answered May 7 by avibootz
0 votes
#include <iostream>
#include <random>
#include <ctime>

int main() {
    // Use the current time as a seed for the random number generator
    std::mt19937 generator(static_cast<unsigned int>(std::time(nullptr)));

    // Define a distribution range
    std::uniform_int_distribution<int> distribution(1, 100);

    // Generate a random number
    int random_number = distribution(generator);

    std::cout << "Random number: " << random_number << std::endl;
}



/*
run:

Random number: 58

*/

 



answered May 7 by avibootz
...