In: Computer Science
In python 3.7:
You’re going to program a simulation of the following game. Like many probability games, this one involves an infinite supply of ping-pong balls. No, this game is "not quite beer pong."
The balls are numbered 1 through N. There is also a group of N cups, labeled 1 through N, each of which can hold an unlimited number of ping-pong balls (all numbered 1 through N). The game is played in rounds. A round is composed of two phases: throwing and pruning.
Every ball drawn has a uniformly random number, every ball lands in a uniformly random cup, and every throw lands in some cup. The game is over when, after a round is completed, there are no empty cups.
After each round, print the non-empty cups and number of balls each hold.
At the end of the simulation you will print the following:
How many rounds would you used to finish this game?
How many balls did you draw and throw to finish this game?
Sort the cups in descending order by the number of balls they hold.
only importing random, no pygame
Hi there,
I have solved the question you provided with all the necessary steps given. I had to use loops to solve the question.
The code :
import random
#counts the number of balls used
no_of_balls=0
#input the number of balls
print("Enter the number of balls and cups : ",end="")
n=int(input())
print("")
cups=[0] * n
cup_has_req_ball = [0] * n
#keep count of the cups filled
cup_filled=0
#counts the number of rounds used
no_of_rounds=0
#to check wehter atleast a single cup is filled
unique_cup=0
#simulation starts
while(1):
print("Starting a new round...")
no_of_rounds+=1
#Throwing starts
while(cup_filled<n):
x=random.randrange(0,n)
y=random.randrange(0,n)
no_of_balls+=1
if cups[x]==0:
cup_filled+=1
cups[x]+=1
if(x==y):
cup_has_req_ball[x]+=1
unique_cup=1
#pruning starts
for i in range(len(cups)):
if(cup_has_req_ball[i] == 0):
cup_filled-=1
cups[i]=0
#print all the non empty cups
if(unique_cup==1):
print("All the non Empty cups and
the number of balls they hold are : ")
for i in range(len(cups)):
if(cup_has_req_ball[i] != 0):
print(str((i+1))+"->"+str(cups[i])+" ",
end="")
print("")
else:
print("No non-empty cups till
now...")
#get out of the loop if all the cups have been
filled
if(cup_filled==n):
print("Game Over")
print("")
break
print("Round over...")
print("")
#print the required information
print("Number of rounds used : "+str(no_of_rounds))
print("Number of balls used : "+str(no_of_balls))
cups.sort(reverse=True)
print("The number of balls in each cups in decending order are:
")
for i in cups:
print(i,end=" ")
print("")
The Code (screenshot):
The Output (screensot) :
Hope you liked the answer. If you have any doubts, do let me know in the comment section.
Happy coding :)