🔓알고리즘/난수생성기

랜덤함수 직접 구현하기 - c++

Mawile 2021. 8. 10.
728x90

이번시간에서는 랜덤 함수를 직접 만드는 방법에 대해서 포스팅하겠습니다.

보통 랜덤값을 구한다고한다면 c에서는 rand(), c++에서는 mt19937을 사용합니다.

 

 

이번에는 좀 귀찮고, 졸려서 빠르게 코드만 올리고 빠지겠습니다.

 

암기요소: 0x7df121, 0x2490f3, 0x9194

 

#include <bits/stdc++.h>

static std::size_t seed = 0;

inline unsigned int GetRandom()
{
	seed = 0x7df121 * seed + 0x2490f3;
	return seed % 0x9194;
}

inline void setSeed(std::size_t seeds) {
	seed = static_cast<std::size_t>(seeds);
}

inline int getRandomNumber(int min, int max)
{
	const double fraction = 1.0 / (RAND_MAX + 1.0);
	int result = min + static_cast<int>((max - min + 1) * (GetRandom() * fraction));
	return ((result > max) ? getRandomNumber(min, max) : result);
}

int main()
{
	setSeed(static_cast<std::size_t>(std::time(0)));

	for (int i = 1; i <= 200; ++i)
	{
		std::cout << getRandomNumber(1, 3) << '\t';
		if (i % 10 == 0) std::cout << '\n';
	}
	return 0;
}

 

 

 


 

728x90

댓글