본문 바로가기
프로그래밍/boost

boost::random

by neive 2012. 10. 24.
728x90

 

http://www.boost.org/doc/libs/1_51_0/doc/html/boost_random.html

boost 에서 랜덤 생성도 제공해 줍니다 rand(time(0)) 을 쓸때 생기는 흔한 (혹은 뻔한) 패턴을 피해서 각자 만들곤

하는데 그런 노고를 안해도 될 듯 하네요

 

1~6 랜덤 숫자 구하기

#include <boost/random.hpp>

int GetDice()
{
	boost::random::mt19937 rng;
	boost::random::uniform_int_distribution<> six(1,6);

	return six(rng);
}

 

특정 숫자 범위내에서 구하기

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>

int GetRand()
{
	boost::random::mt19937 gen;
    boost::random::uniform_int_distribution<> dist(1, 6);
    
	return dist(gen);
}

 

랜덤 패스워드 구하기

#include <boost/random/random_device.hpp>
#include <boost/random/uniform_int_distribution.hpp>

void Password()
{
	std::string chars(
		"abcdefghijklmnopqrstuvwxyz"
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		"1234567890"
		"!@#$%^&*()"
        "`~-_=+[{]{\\|;:'\",<.>/? ");

	boost::random::random_device rng;
    boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1);
	
	for(int i = 0; i < 8; ++i)
		std::cout << chars[index_dist(rng)];

	std::cout << std::endl;
}
728x90

댓글