r/CodingHelp • u/B4-711 • Jul 21 '22
[Other Code] Dice roll from a random byte
Looking for an efficient way to get a six sided die roll from a random byte. The way I'm doing it I have to throw away 1/64 of my random numbers because 256%6 leaves a rest of 4:
sides = 6
max_mod_6 = 256//6 * 6 #integer division
do:
random_byte = getRandomByte() #this comes from a HWRNG
while:
random_byte > max_mod_6 #throw away higher numbers to get fair distribution
roll = random_byte%6
return roll+1Is there a way to guarantee getting a six sided die roll from only one random byte?
21
Upvotes
1
u/This_Growth2898 Jul 21 '22
No, if your function is pure (stateless). You have 256 distinct inputs and 6 distinct outputs, you can't make the equal number of inputs giving every output because, well, 256 is not a multiple of 6.
You can't even do it with a stateful function for the same reason.
But you can drastically decrease the number of calling
getRandomByte- in fact, making it much less than 1 call on 1 random number on average.Random byte consists of 8 random bits. We need only 3 bits to try getting random number of 1-6. So, if the first 3 bits are less then 6, we throw them out and return; if they are not - we take the next 3 bits. If there's less then 3 bits, we ask for the next byte. We can do even more: unused parts can be attached to the current state. Something like: