Skip to content

Commit 8a554f5

Browse files
committed
Support any integral or real type in randint()
1 parent c1b6ca8 commit 8a554f5

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/engine/global.h

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
#include "blockargs.h"
66
#include <functional>
7-
#include <vector>
7+
#include <random>
88

99
/*! \brief The main namespace of the library. */
1010
namespace libscratchcpp
@@ -18,14 +18,22 @@ namespace libscratchcpp
1818
using BlockImpl = std::function<Value(const BlockArgs &)>;
1919

2020
/*! Generates a random number in the given interval like the random.randint() function in Python. */
21-
inline int randint(int start, int end)
21+
template<typename T>
22+
inline T randint(T start, T end)
2223
{
2324
if (start > end) {
24-
int tmp = start;
25+
auto tmp = start;
2526
start = end;
2627
end = tmp;
2728
}
28-
return rand() % (end - start + 1) + start;
29+
std::default_random_engine generator;
30+
if constexpr (std::is_integral<T>()) {
31+
std::uniform_int_distribution<T> distribution(start, end);
32+
return distribution(generator);
33+
} else {
34+
std::uniform_real_distribution<T> distribution(start, end);
35+
return distribution(generator);
36+
}
2937
}
3038

3139
} // namespace libscratchcpp

0 commit comments

Comments
 (0)