How to generate uniform random integers in a range with C++

1 Answer

0 votes
#include <iostream>
#include <random>

int main() {
    std::random_device rd;

    // Seed a Mersenne Twister PRNG with the random device.
    // mt19937 is high‑quality, fast, and widely used.
    std::mt19937 gen(rd());

    // Define the desired range [low, high].
    int low = 10;
    int high = 50;

    // Create a uniform integer distribution over the range.
    // This guarantees each number in [low, high] is equally likely.
    std::uniform_int_distribution<int> dist(low, high);

    // Generate and print 10 random numbers.
    for (int i = 0; i < 10; i++) {
        int value = dist(gen);   // draw a number from the distribution
        std::cout << value << " ";
    }
}



/*
run:

20 38 24 14 22 46 50 21 42 11 

*/

 



answered Jan 4 by avibootz
...