diff options
author | Stefan O'Rear <stefanor@cox.net> | 2009-11-08 09:45:24 -0800 |
---|---|---|
committer | Stefan O'Rear <stefanor@cox.net> | 2009-11-08 09:45:24 -0800 |
commit | 615038114f0c6502b2ce3c76bf71ce4fb6f1a8e5 (patch) | |
tree | d93f833bfc7b4398945b565ca3c593421df43fc1 /crawl-ref/source/random.cc | |
parent | d591b006258fea1c86eee54e7dc18086a6e6b862 (diff) | |
download | crawl-ref-615038114f0c6502b2ce3c76bf71ce4fb6f1a8e5.tar.gz crawl-ref-615038114f0c6502b2ce3c76bf71ce4fb6f1a8e5.zip |
Remove the bias from random2()
Worst case for the old version was random2(65535) == 65534, which had a
1 in 2^30 chance of being true.
Diffstat (limited to 'crawl-ref/source/random.cc')
-rw-r--r-- | crawl-ref/source/random.cc | 11 |
1 files changed, 10 insertions, 1 deletions
diff --git a/crawl-ref/source/random.cc b/crawl-ref/source/random.cc index fad30322de..758f5ea599 100644 --- a/crawl-ref/source/random.cc +++ b/crawl-ref/source/random.cc @@ -95,7 +95,16 @@ int random2(int max) if (max <= 1) return (0); - return (static_cast<int>(random_int() / (0xFFFFFFFFUL / max + 1))); + unsigned long partn = 0xFFFFFFFFUL / max; + + while (true) + { + unsigned long bits = random_int(); + unsigned long val = bits / partn; + + if (val < (unsigned long)(max)) + return val; + } } bool coinflip(void) |