From 13649778c1fc4ffba0d51368f231fc2ff1a0c86d Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 8 Jan 2017 00:53:23 +0100 Subject: [PATCH] random.nim: added shuffle proc; fixes 'mod' bias --- lib/pure/random.nim | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/pure/random.nim b/lib/pure/random.nim index 67f085dac5..9484557a9f 100644 --- a/lib/pure/random.nim +++ b/lib/pure/random.nim @@ -1,7 +1,7 @@ # # # Nim's Runtime Library -# (c) Copyright 2016 Andreas Rumpf +# (c) Copyright 2017 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -22,6 +22,8 @@ when defined(JS): else: type ui = uint64 +const randMax = 18_446_744_073_709_551_615u64 + type RandomGenState = object a0, a1: ui @@ -72,7 +74,10 @@ proc random*(max: int): int {.benign.} = ## random number is always the same, unless `randomize` is called ## which initializes the random number generator with a "random" ## number, i.e. a tickcount. - result = int(next(state) mod uint64(max)) + while true: + let x = next(state) + if x < randMax - (randMax mod uint64(max)): + return int(x mod uint64(max)) proc random*(max: float): float {.benign.} = ## Returns a random number in the range 0..