Three digit random number generator

Hello,

Does anyone know how to produce a code that will satisfy the following constraints. I don't really know C++


- Produces a random three number positive integer between 001 - 504.

- Changes the output number every 24 hours on a website. (Not sure if it's even possible; I have no idea.)

Any help is appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <random>
#include <chrono>

// returns a pseudo-random number in [001,505).
// changes the random number every 24 hours
int random_number()
{
    using namespace std::chrono ;

    // the time point at which the random number was generated
    static auto timestamp = steady_clock::now() ;

    // the random engine and distribution
    static std::mt19937 twister( timestamp.time_since_epoch().count() ) ;
    static std::uniform_int_distribution<int> distribution(1,504) ;

    static int random = distribution(twister) ; // initial value

    auto time_now = steady_clock::now() ; // current time

    // if 24 hors have passed since the last random number was generated
    if( duration_cast<hours>( time_now - timestamp ) > hours(24) )
    {
        timestamp = time_now ; // update the timestamp
        random = distribution(twister) ; // ang generate a new random number
    }

    return random ;
}
Well what jlborges had done using c++11 is quite better anyways but here's a rather simplistic way of doing so.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include<cstdlib>
#include<ctime>
int random_num(int lo,int hi)
{
       return rand()%(hi-lo) + lo;
}
int main()
{
      srand(time(NULL));
      std::cout << random_num(1,504);
      return 0;
}
Last edited on
Topic archived. No new replies allowed.