Friday, 8 October 2021

Program in python to generate a random integer from 1 to 16 with a single six-sided die

I am writing a program in Python where you generate a random integer from 1 to 16 inclusive where your only random number generator is a six-sided die. Assuming a function named roll6 which returns a 1, 2, 3, 4, 5, or 6, and then writing a function named roll16 which returns an integer between 1 and 16 inclusive.
I wrote the below code that generates the random integer using 3 dices but stuck on doing the same with a single dice:


import random

# Roll6 function to return random number between 1 and 6
def roll6():
    return(random.randint(1,6))

# Roll16 function to call Roll6 function thrice while re 
# rolling the dice when total is over 16
# Our range with 3 dices are 3 - 18, so I am deducting 2 to set the range from 1 to 16
def roll16():
    value = (roll6() + roll6() + roll6()) - 2
    return value

# Print the random value returned by roll16
i = roll16()
while i != 1:
    print(i)
    i = roll16()
print(I)

Any idea on how to do this with a single dice? Thanks.



from Program in python to generate a random integer from 1 to 16 with a single six-sided die

No comments:

Post a Comment