Here is the setup: Assume a standard shuffled deck of 52 cards. Use only Monte Carlo method to calculate the approximate probability that the first two cards in the deck are aces. At the beginning of your implementation, set your seed to be 514. You should simulate at least 100 thousand experiments to get an approximate enough answer.
Here is my code that is returning the error:
cards <- c(1:52)
nTrials<-100000
results <-rep(NA, nTrials)#creating empty vector with 100000 NAs
for(i in 1:nTrials){
sampled <- sample(x=cards, size=2, replace=TRUE)
results[i]<-sampled
}
results
You are sampling two card in each iteration of for
loop. So you would have 2 *nTrials
cards at the end which is double the size of results
assigned. Store the cards in a list instead.
Let's assume that card number 1,14,27 & 40 are aces. You can check if the sampled cards are ace with %in%
and increment the counter if they are.
cards <- c(1:52)
aces <- c(1, 14, 27, 40)
nTrials<-100000
results <- vector('list', nTrials)
counter <- 0
for(i in 1:nTrials){
sampled <- sample(x=cards, size=2, replace=TRUE)
results[[i]] <- sampled
if(all(sampled %in% aces)) counter <- counter + 1
}
#Number of times two aces were enountered
counter
#Probability
counter/nTrials