Use python to write the code
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.
import random N = 5 # Create a list of list to contain all cups. # cups[i-1] contains the contents of cup i. (as index starts from 0 and not 1, 1st cup is cups and so on) cups = [ for i in range(N)] rounds = 0 balls = 0 # game is True as long as the game goes on game = True # Number of empty cups. The game ends when empty == 0 at end of a round. empty = N while(game): rounds+=1 print("Round :", rounds) # Throwing phase # Continue throwing round while there is atleast one empty cup while(empty != 0): # Randomly select the ball and the cup. # We subtract 1 from cup as we need it to correspond to indices of cups list. ball = random.randint(1, N) cup_number = random.randint(0, N-1) # Check if current cup is empty, if it is reduce number of empty cups as we # are going to put a ball in it. if(len(cups[cup_number]) == 0): empty-=1 cups[cup_number].append(ball) balls+=1 #Throwing phase ends. # Start Pruning phase # Remove any balls that do not match the cup number #Currently empty is 0. for i in range(N): # Use filter function to filter elements having same number as cup number filtered_cup = filter(lambda x : x==i+1, cups[i]) cups[i] = (list)(filtered_cup) if len(cups[i]) == 0: empty+=1 else: print("Cup",i+1,"is non empty and has",len(cups[i]),"ball(s)") # Pruning phase ends. print("") # If no cup is empty, game is completed. if(empty == 0): game = False # Printing end game stats. print("After the game ends -") print("rounds =",rounds) print("balls =", balls) # Sort the cups in descending order of balls they hold. cups = sorted(cups, key = lambda x: len(x), reverse = True) print("Contents of cups") for cup in cups: print(cup)
I have set N = 5, you can change the value of N as you see fit.
I have added comments for your understanding.
I would love to resolve any queries in the comments. Please consider dropping an upvote to help out a struggling college kid :)
Happy Coding !!
Get Answers For Free
Most questions answered within 1 hours.