Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a random integer that is perpetually changing?

How can I create a pseudo-randomized integer that is constantly changing? This way, I could enter:

cout << randomInt << endl;
cout << randomInt << endl;
cout << randomInt << endl;

and the program would return something like:

45.7
564.89
1.64

(I'm not sure if any of this makes any sense.)

like image 381
user1892304 Avatar asked Dec 01 '22 04:12

user1892304


2 Answers

Create a class representing the Random number:

class Random {
};

Then overload operator<<:

std::ostream& operator<<(std::ostream& os, const Random& random) {
    return os << generate_random();
}

Use as:

int main() {
    Random random;
    std::cout << random; 
    std::cout << random; 
    std::cout << random; 
    return 0;
}

Obviously, you need to implement generate_random.

like image 118
Peter Wood Avatar answered Dec 02 '22 16:12

Peter Wood


Using the new C++11 pseudo-random number generation classes:

#include <random>
#include <iostream>
int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 6);
    for(int n=0; n<10; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

The above simulates ten dice rolls.

If you want floating-point values instead of integers, use std::uniform_real_distribution instead of std::uniform_int_distribution.

like image 22
Some programmer dude Avatar answered Dec 02 '22 18:12

Some programmer dude