# The Six Glass Problem From Presh Talwalkar

I have enjoyed the videos by Presh Talwalkar and I think he does an excellent job of bringing some interesting problems to a broad audience. I highly recommend his videos because they are quite engaging and I’ll be doing a book review on some of his offerings soon.

In a recent video, he posted about a problem with six glasses and a single die. When you roll the die, the corresponding numbered glass gets filled. If it’s already filled, then you drink the glass and it becomes empty. So the problem set is: How many rolls on average it take to have all 6 glasses filled at the same time? While Presh does a great job of explaining the math behind this problem, there’s always more than one way to solve these. In this article, I present a Julia solution to the exact same problem. If you walk through the Julia code, you will see that you can generate the same answer that is presented in the video.

For some of us, writing out the code might be a little faster than working through all of the math! Either way, it’s good to know multiple approaches to the same problem because you never know when you’ll need one approach over the other. Items like this also make for great practice when learning a new coding language like Julia and I’m happy to present the entire script below.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | # Copyright 2016 buriedinfo.com # Written by Dennis Salguero rollCollection = Int[] # Keep all the rolls in one place for epoch = 1:100000 # The primary loop # Empty the glasses glasses = Int[0,0,0,0,0,0] rollCounter = 0 # Keep track of the rolls for this epoch # Give this loop a high number, we'll be breaking the loop anyways for endlessRoll = 1:30000 diceRoll = rand(1:length(glasses)) # Get a random number # Adjust the chosen glass accordingly if glasses[diceRoll]==0 glasses[diceRoll]=1 elseif glasses[diceRoll]==1 glasses[diceRoll]=0 end #How many glasses are filled? filled = count(x->x==1, glasses) # Are ALL the glasses filled? if filled==length(glasses) # Game is over for this epoch, add the number of rolls to the array push!(rollCollection,endlessRoll) break # Break out of the loop and start a new epoch end end end println("Average rolls: ", sum(rollCollection)/length(rollCollection)) |