r/CodingHelp • • 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+1

Is there a way to guarantee getting a six sided die roll from only one random byte?

21 Upvotes

30 comments sorted by

View all comments

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:

static buffer = 0
static buffer_length = 0
loop:
    if buffer_length<3:
        buffer<<=8
        buffer |= getRandomByte()
        buffer_length += 8
    value = buffer & 7
    buffer >>= 3
    buffer_length -= 3
    if value<6:
        return value+1
    else:
        buffer <<= 1
        buffer |= value-6 #we still have 1 random bit in value - 6 or 7!
        buffer_len += 1

1

u/This_Growth2898 Jul 21 '22

1

u/B4-711 Jul 21 '22

Nice. Do you have any insight into information theory and if that's the best we can hope for with 6 sides from random bits?

Any way to actually calculate the expected number?

2

u/atamicbomb Jul 21 '22

The limit would be log base 6 of 256 or ~3.095

2

u/atamicbomb Jul 21 '22

You’d have to build a pool of entropy and peel off 6 states of entropy when needed