This question concerns the generation of, and use of, pseudo random numbers. (i
ID: 3800820 • Letter: T
Question
Explanation / Answer
Part i)
#include <iostream>
using namespace std;
class RandomGen
{
public:
void seed(unsigned int s)
{
_seed = s;
}
protected:
RandomGen() :
_seed(0), _a(0), _b(0), _m(2147483648)
{
}
int rnd()
{
return (_seed = (_a * _seed + _b) % _m);
}
int _a, _b;
unsigned int _m, _seed;
};
class MsRandomGen: public RandomGen
{
public:
MsRandomGen()
{
_a = 16807;
_b = 2147483647;
}
int rnd()
{
return RandomGen::rnd() >> 16;
}
};
int main(int argc, char* argv[])
{
MsRandomGen ms_rnd;
cout << " RAND:" << endl << "========" << endl;
for (int x = 0; x < 10; x++)
cout << ms_rnd.rnd() << endl;
return 0;
}
========================================================
akshay@akshay-Inspiron-3537:~/Chegg$ g++ linearrando.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
RAND:
========
32767
32767
28457
3697
22003
30691
2027
25429
27597
3728
=========================================================
Part ii
#include <iostream>
using namespace std;
class RandomGen
{
public:
void seed()
{
_seed = clock();
}
protected:
RandomGen() :
_seed(), _a(0), _b(0), _m(2147483648)
{
}
int rnd()
{
return (_seed = (_a * _seed + _b) % _m);
}
int _a, _b;
unsigned int _m, _seed;
};
class MsRandomGen: public RandomGen
{
public:
MsRandomGen()
{
_a = 16807;
_b = 2147483647;
}
int rnd()
{
return RandomGen::rnd() >> 16;
}
};
int main(int argc, char* argv[])
{
MsRandomGen ms_rnd;
cout << " RANDOM Numbers in range 1 to 50:" << endl << "========" << endl;
for (int x = 0; x < 5; x++)
cout << ms_rnd.rnd()%50+1 << endl;
cout << " RANDOM Numbers in range 1 to 9:" << endl << "========" << endl;
for (int x = 0; x < 2; x++)
cout << ms_rnd.rnd()%9+1 << endl;
return 0;
}
==============================================================
akshay@akshay-Inspiron-3537:~/Chegg$ g++ linearrando.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
RANDOM Numbers in range 1 to 50:
========
18
18
8
48
4
RANDOM Numbers in range 1 to 9:
========
2
3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.