######################################################################
#
# Yahtzee in R
#
# Rules of Yahtzee (Simplified)
#
# * Roll five dice, and re-roll some of them until you get a Yahtzee (meaning that all five dice show the same number).
# * Roll five dice. Suppose we get 1,2,1,3,1.
# * Keep the values that occur the most. In our example, we have three 1s. This is our "current Yahtzee."
# * Re-roll the other dice. In this case, we re-roll the two dice that were not 1s. Suppose we get 1 and 4.
# * Add to the current Yahtzee. In our example, we have 1,1,1,1,4. Return to second step and repeat until all the values are the same, in which case we have a Yahtzee.
#
# Question: On average, how many rolls are required to get a Yahtzee?
#
# Let's explore this question using R.
#
######################################################################
##### Rolling Dice #####
# The sample function can simulate rolling a die:
sample(1:6, 1)
# The sample function can also simulate rolling many dice:
sample(1:6, 5, replace=T)
# We can write our own function to make this a bit simpler to use:
myDice <- function(n){
sample(1:6, n, replace=T)
}
##### Simulate rolling for a Yahtzee #####
totRolls <- 0 # we haven't yet rolled
currMatches <- c() # no matches to start
totMatches <- length(currMatches) # total matches
# First, roll five dice and store the result in currMatches.
# Now select the most common match and update totMatches.
# Some useful ideas:
# sum(myVec == i) counts the number of times i occurs in myVec
# max(myVec) gives the maximum entry in myVec
# which.max(myVec) gives an index of the maximum entry in myVec
# Repeat the dice-rolling process while totMatches is less than 5.
# Make sure you count the number of rolls that it took to get a Yahtzee!
##### Package your code into a function that simulates a game of Yahtzee #####
##### Once you get the function working, simulate the game many times
##### and record how many rolls it takes to get a Yahtzee.
##### Based on your simulations, answer the following questions:
# What is the mean number of rolls?
# What proportion of the time do you get Yahtzee in three or fewer rolls?
# Can you make a histogram of the number of rolls until you get Yahtzee?