rand, arc4random, random
C++ã§ã®ä¹±æ°ã®ä½¿ãæ¹ãã¾ã¨ãã¨ãã
rand, srand
Cã®æ¨æºã©ã¤ãã©ãª
0以ä¸, RAND_MAX以ä¸ã®æ´æ°ä¹±æ°ãçºçãããã
è¯ãããã®ã¯
time_t time(time_t *timer);
ã使ãããæ¹ãå¼æ°ã®timerã«ã¯æ»ãå¤ã¨åãç¾å¨ã®æ¦æå»ã代å
¥ãããã
å¿
è¦ãªãããã¬ãã½ãããã¨ãããkã
ãã ããã°ãã¼ãã«é¢æ°ã使ã£ã¦ãã®ã§ãããã°ã©ã å
¨ä½ã§ä¸ã¤ã®ä¹±æ°çæå¨ããå©ç¨ã§ããªãã
ã·ãã¥ã¬ã¼ã·ã§ã³ç¨éã ã¨ãåç¾æ§ãä¿è¨¼ããããã®ç¶æ
管çãããããããªãã
RAND_MAX: 2147483647 ã¾ã§ã®ä¸æ§ä¹±æ°ããçæã§ããªãã
ä¹±æ°ã®è³ªããã¾ãè¯ããªããããã
ä¹±æ°ã®ç¯å²ã¯ãå°ä½æ¼ç®ã§å¶å¾¡ã§ããã
srand(static_cast<unsigned>(time(nullptr))); //srandå¼ã°ãªãã¨æ¯ååãçµæã«ãªã std::cout << "max: " << RAND_MAX << std::endl; REP(i, LOOP) std::cout << rand()%(MAX+1) << " "; std::cout << std::endl;
arc4random
ANSI Cã«ã¯ãªãã®ã§ã使ããªãå ´åãããã
iOS/Macã§ã¯ä½¿ãã¦ã¾ãã
randã¨éã£ã¦ãã·ã¼ããè¨å®ããå¿
è¦ããªãã
arc4random_stir é¢æ°ãã /dev/urandom ãããã¼ã¿ãèªã¿åãã
ããã使ç¨ã㦠Fn arc4random_addrandom ã«ãã£ã¦ S-Box ã®é åºãå¤ããã
ãªãã»ã©ãããããã
ã¨ã«ããã
arc4randomã¯èªåèªèº«ã§åæåãããããarc4random_stirãå¼ã¶å¿
è¦ã¯ãªãã
/dev/urandomãããã¼ã¿ãèªã¿åãã£ã¦æ¸ãã¦ãããããboost::random_device()ã¨åããããªãããªã®ããª?
é決å®æ§ãåæåã®å¿
è¦ã¯ãªãã
REP(i, LOOP) std::cout << arc4random()%(MAX+1) << " "; std::cout << std::endl;
random
C++11ã ã¨ä½¿ããã¯ãã ãã©ãBoost Randomã¨å°ãéãç¹ãããã
seedã®è¨å®ã«ã¯seed_seqã使ãã
seed_seqã®ã³ã³ã¹ãã©ã¯ã¿ã¯åæåç¨ãã¯ã¿ã®ã¤ãã¬ã¼ã¿ãã¨ãã
åæåç¨ã®ãã¯ã¿ã®é·ãã¯ãããã§ãããã¿ãããé·ãã¦ããå
¨è¦ç´ ã使ãããã¨ã¯éããªãã
å¥ã«ã·ã¼ãã¯seed_seqã§ãªãã¦ãããã¿ãããªã®ã§ãstd::random_deviceã¨ãarc4random()ã¨ãtime(nullptr)ã¨ãã§ãè¯ãæ°ãããã
std::random_device rnd; //std::mt19937_64 rnd; std::vector< std::uint_least32_t > v(10); //åæç¨ãã¯ã¿ std::generate( v.begin(), v.end(), std::ref(rnd) ); //algorithm generateã使ã£ã¦ãåæç¨ãã¯ã¿ãåãã std::seed_seq seed(v.begin(), v.end()); std::mt19937 engine( seed ); //std::mt19937 engine(rnd()); std::uniform_real_distribution<> distribution(0, 1.0); std::cout << "min: " << engine.min() << " max: " << engine.max() << std::endl; REP(i,10) std::cout << engine() << std::endl; std::cout << std::endl; std::cout << "min: " << rnd.min() << " max: " << rnd.max() << std::endl; REP(i,10) std::cout << distribution(engine) << std::endl; std::cout << std::endl;
Boost.Randomã¨ã®å¤§ããªéãã¯ãvariate_generator
ãªã®ã§ããããªæãã«bindã使ã£ã¦æ¸ãããããã
auto myrnd = std::bind( std::uniform_real_distribution<double>(0.0, 1.0), std::mt19937(arc4random()) ); REP(i,10) std::cout << myrnd() << std::endl;