-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandom.cpp
More file actions
123 lines (112 loc) · 2.36 KB
/
Random.cpp
File metadata and controls
123 lines (112 loc) · 2.36 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include "Random.h"
#include "main.h"
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <random>
#include <stdexcept>
#include <string>
using ::std::cout;
using ::std::default_random_engine;
using ::std::endl;
using ::std::invalid_argument;
using ::std::ostream;
using ::std::out_of_range;
using ::std::string;
using ::std::string_view;
using ::std::uniform_int_distribution;
long fromCString(const char* pStr)
{
string str{pStr};
try
{
size_t endIndex;
auto result = stol(str, &endIndex);
if (endIndex != str.size())
{
throw invalid_argument(
"Numeric argument with trailing non-numeric characters");
}
return result;
}
catch(const invalid_argument& ex)
{
string msg{"Invalid numeric format ('"};
msg += str;
msg += "'): ";
msg += ex.what();
throw CmdLineError(msg);
}
catch(const out_of_range&)
{
string msg{"Out-of-range number ('"};
msg += str;
msg += "')";
throw CmdLineError(msg);
}
}
#if !defined(CMDLINEUTIL_TEST_MODE)
int main(int argCount, const char*const*const argList)
{
return commonMain<Random>(argCount, argList);
}
#endif
int Random::usage(ostream& out, string_view progName, const char* pMsg)
{
int exitCode = EXIT_SUCCESS;
if (pMsg != nullptr && *pMsg != '\0')
{
exitCode = EXIT_FAILURE;
out << endl << pMsg << endl;
}
out << "\n"
"Usage: " << progName << " <lower-bound> <upper-bound> [ <count> ]\n"
"\n"
"Generates <count> uniformly distributed random integers\n"
"between <lower-bound> and <upper-bound>. The two bounds\n"
"are required, and <count> defaults to one.\n"
<< endl;
return exitCode;
}
Random::Random(::std::span<const char*const> args) :
m_lowerBound(0),
m_upperBound(0),
m_count(1)
{
if (args.size() < 3)
{
throw CmdLineError("Too few arguments");
}
else if (args.size() > 4)
{
throw CmdLineError("Too many arguments");
}
else
{
m_lowerBound = fromCString(args[1]);
m_upperBound = fromCString(args[2]);
if (args.size() == 4)
{
m_count = fromCString(args[3]);
}
}
if (m_count <= 0)
{
m_count = 1;
}
}
int Random::run() const
{
for (long i = 0; i < m_count; ++i)
{
cout << getRandomInteger(m_lowerBound, m_upperBound) << endl;
}
return EXIT_SUCCESS;
}
long Random::getRandomInteger(long low, long high)
{
default_random_engine generator;
uniform_int_distribution<long> distribution(low, high);
return distribution(generator);
}