Last active
August 29, 2015 14:02
-
-
Save mitsu-ksgr/72a3b55d1cdb9b02a17e to your computer and use it in GitHub Desktop.
C++11で追加された乱数機能をちょっぴり使いやすく。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <random> | |
#include <limits> | |
/** | |
* @brief ランダムな整数を生成する関数を作成します。 | |
* @tparam T 実数型(short, int, long...)。省略時は unsigned int. | |
* @param min 乱数最小値。省略時は0が指定される。 | |
* @param max 乱数最大値。省略時はT型の最大値が指定される。 | |
* @return 整数乱数生成関数 | |
* @author Mitsu | |
*/ | |
template<typename T = unsigned int> | |
inline std::function<T(void)> getIntRandEngine( | |
T min = 0, T max = std::numeric_limits<T>::max()) | |
{ | |
std::random_device rd; | |
std::mt19937 engine(rd()); | |
std::uniform_int_distribution<T> dist(min, max); | |
return std::bind(dist, engine); | |
} | |
/** | |
* @brief ランダムな実数を生成する関数を作成します。 | |
* @tparam T 実数型(float, double)。省略時はdouble。 | |
* @param min 乱数最小値。省略時は0.0が指定される。 | |
* @param max 乱数最大値。省略時は1.0が指定される。 | |
* @return 実数乱数生成関数 | |
* @author Mitsu | |
*/ | |
template<typename T = double> | |
inline std::function<T(void)> getRealRandEngine(T min = 0.0, T max = 1.0) | |
{ | |
std::random_device rd; | |
std::mt19937 engine(rd()); | |
std::uniform_real_distribution<T> dist(min, max); | |
return std::bind(dist, engine); | |
} | |
int main() | |
{ | |
// Test1: integer. | |
std::cout << "getIntRandEngine()" << std::endl; | |
auto getRandI = getIntRandEngine(); | |
for(int i = 10; --i >= 0;) | |
std::cout << " - " << getRandI() << std::endl; | |
// Test2: Dice | |
std::cout << "getIntRandEngine(1, 6)" << std::endl; | |
auto getDice = getIntRandEngine(1, 6); | |
for(int i = 10; --i >= 0;) | |
std::cout << " - " << getDice() << std::endl; | |
// Test3: double | |
std::cout << "getRealRandEngine()" << std::endl; | |
auto getRandD = getRealRandEngine(); | |
for(int i = 10; --i >= 0;) | |
std::cout << " - " << getRandD() << std::endl; | |
// Test4: float | |
std::cout << "getRealRandEngine<float>()" << std::endl; | |
auto getRandF = getRealRandEngine<float>(); | |
for(int i = 10; --i >= 0;) | |
std::cout << " - " << getRandF() << std::endl; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment