Skip to content

Commit

Permalink
fixed randomNumber's frontwards bias (#26)
Browse files Browse the repository at this point in the history
Before in randomNumber return crypto.randomBytes(1)[0] % max;
was used to generate the random number. Using modulo at the
end does lead to a bias in the probability distribution of the
generated characters if the character count does not divide 256.
E.g. if using randomNumber(255) the number 0 is twice as likely
as all other numbers and thus the character 'a' will appear
much more frequently.

The fix is to discard the random value if it is above the highest
mulitple of the character count that is not greater than 256.
  • Loading branch information
Starkteetje authored and brendanashworth committed Oct 28, 2018
1 parent 4d40444 commit 21a12d0
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ var self = module.exports;
// Generates a random number
var randomNumber = function(max) {
// gives a number between 0 (inclusive) and max (exclusive)
return crypto.randomBytes(1)[0] % max;
var rand = crypto.randomBytes(1)[0];
while (rand >= 256 - (256 % max)) {
rand = crypto.randomBytes(1)[0];
}
return rand % max;
};

// Possible combinations
Expand Down

0 comments on commit 21a12d0

Please sign in to comment.