First we set up the chocolate randomisation process, but this time making 25% of the bars Cherry Ripe:
chocolate_types<-c("Cherry Ripe","Dairy Milk","Crunchie", "Caramello","Flake")
make_pack<-function(){
sample(chocolate_types, 8, replace=TRUE, prob=c(25,19,19,18,19))
}
make_pack()
## [1] "Flake" "Flake" "Caramello" "Dairy Milk" "Dairy Milk"
## [6] "Caramello" "Cherry Ripe" "Crunchie"
make_pack()
## [1] "Flake" "Cherry Ripe" "Caramello" "Dairy Milk" "Cherry Ripe"
## [6] "Cherry Ripe" "Cherry Ripe" "Caramello"
replicate(5, make_pack())
## [,1] [,2] [,3] [,4] [,5]
## [1,] "Cherry Ripe" "Dairy Milk" "Cherry Ripe" "Caramello" "Cherry Ripe"
## [2,] "Cherry Ripe" "Crunchie" "Dairy Milk" "Crunchie" "Crunchie"
## [3,] "Dairy Milk" "Cherry Ripe" "Crunchie" "Flake" "Cherry Ripe"
## [4,] "Flake" "Dairy Milk" "Flake" "Cherry Ripe" "Caramello"
## [5,] "Cherry Ripe" "Cherry Ripe" "Cherry Ripe" "Cherry Ripe" "Dairy Milk"
## [6,] "Flake" "Caramello" "Flake" "Cherry Ripe" "Cherry Ripe"
## [7,] "Cherry Ripe" "Dairy Milk" "Dairy Milk" "Cherry Ripe" "Crunchie"
## [8,] "Cherry Ripe" "Cherry Ripe" "Cherry Ripe" "Flake" "Flake"
Now, we need to work out which bar we have the most of, and count them
count_most<-function(a_pack){
count <- table(a_pack)
most <- which.max(count)
count[most]
}
a_test_pack<-make_pack()
a_test_pack
## [1] "Crunchie" "Caramello" "Flake" "Cherry Ripe" "Caramello"
## [6] "Flake" "Flake" "Crunchie"
count_most(a_test_pack)
## Flake
## 3
We’re going to do this lots of times, so we need a function that asks how many times and then does it:
make_and_count_most<-function(how_many){
replicate(how_many,{
pack<-make_pack()
count_most(pack)
})
}
make_and_count_most(3)
## Crunchie Flake Crunchie
## 3 3 4
And, finally, we take advantage of the power of modern computing by running this a whole heap of times. For curiosity – because the code was written to be clear, not to be fast – I’ll also see how long it takes on my three-year old laptop.
a_whole_heap <- 1e5
system.time(results <- make_and_count_most(a_whole_heap))
## user system elapsed
## 13.319 0.032 13.352
table(results)
## results
## 2 3 4 5 6 7 8
## 15230 55283 23510 5159 739 76 3
table(results[names(results)=="Cherry Ripe"])
##
## 2 3 4 5 6 7 8
## 4784 17942 8713 2336 420 47 3