fix infinite check bug
[rofl0r-oopoker.git] / random.cpp
blobff62a9e0d546dfb670e12e9114b1c92783eb35f8
1 /*
2 OOPoker
4 Copyright (c) 2010 Lode Vandevenne
5 All rights reserved.
7 This file is part of OOPoker.
9 OOPoker is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
14 OOPoker is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with OOPoker. If not, see <http://www.gnu.org/licenses/>.
23 #include "random.h"
25 #if defined(_WIN32)
27 #include <windows.h>
28 #include <iostream>
30 unsigned int getRandomUint()
32 unsigned int r;
34 HMODULE hLib=LoadLibrary("ADVAPI32.DLL");
35 if (hLib) {
36 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
37 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(hLib,"SystemFunction036");
38 if (pfn) {
39 char buff[4];
40 ULONG ulCbBuff = sizeof(buff);
41 if(pfn(buff,ulCbBuff)) {
43 // use buff full of random goop
45 r = buff[0] + 256 * buff[1] + 256 * 256 * buff[2] + 256 * 256 * 256 * buff[3];
50 FreeLibrary(hLib);
53 return r;
56 #elif defined(linux) || defined(__linux) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__)
58 #include <string>
59 #include <fstream>
61 unsigned int getRandomUint()
63 unsigned int r;
64 static std::string filename = "/dev/urandom";
65 static std::ifstream file(filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
66 file.read((char*)(&r), sizeof(r));
67 return r;
70 #endif
72 double getRandom()
74 return getRandomUint() / 4294967296.0;
77 int getRandom(int low, int high)
79 return getRandomUint() % (high - low + 1) + low;
83 static unsigned int m_w = 1;
84 static unsigned int m_z = 2;
86 //"Multiply-With-Carry" generator of G. Marsaglia
87 unsigned int getRandomUintFast()
89 m_z = 36969 * (m_z & 65535) + (m_z >> 16);
90 m_w = 18000 * (m_w & 65535) + (m_w >> 16);
91 return (m_z << 16) + m_w; //32-bit result
94 void seedRandomFast(unsigned int seed1, unsigned int seed2)
96 if(seed1 == 0) seed1 = 1;
97 if(seed2 == 0) seed2 = 1;
98 m_w = seed1;
99 m_z = seed2;
102 void seedRandomFastWithRandomSlow()
104 seedRandomFast(getRandomUint(), getRandomUint());
107 double getRandomFast()
109 return getRandomUintFast() / 4294967296.0;
112 int getRandomFast(int low, int high)
114 return getRandomUintFast() % (high - low + 1) + low;