First we set up the chocolate randomisation process:
chocolate_types<-c("Cherry Ripe","Dairy Milk","Crunchie", "Caramello","Flake")
make_pack<-function(){
sample(chocolate_types, 8, replace=TRUE)
}
make_pack()
## [1] "Dairy Milk" "Flake" "Dairy Milk" "Crunchie" "Flake"
## [6] "Crunchie" "Caramello" "Flake"
make_pack()
## [1] "Caramello" "Crunchie" "Crunchie" "Flake" "Crunchie"
## [6] "Caramello" "Dairy Milk" "Dairy Milk"
replicate(5, make_pack())
## [,1] [,2] [,3] [,4] [,5]
## [1,] "Dairy Milk" "Dairy Milk" "Crunchie" "Crunchie" "Cherry Ripe"
## [2,] "Dairy Milk" "Flake" "Cherry Ripe" "Crunchie" "Flake"
## [3,] "Flake" "Caramello" "Cherry Ripe" "Caramello" "Dairy Milk"
## [4,] "Dairy Milk" "Cherry Ripe" "Cherry Ripe" "Crunchie" "Dairy Milk"
## [5,] "Flake" "Flake" "Flake" "Flake" "Crunchie"
## [6,] "Dairy Milk" "Caramello" "Cherry Ripe" "Caramello" "Dairy Milk"
## [7,] "Flake" "Caramello" "Flake" "Dairy Milk" "Cherry Ripe"
## [8,] "Dairy Milk" "Dairy Milk" "Crunchie" "Crunchie" "Dairy Milk"
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] "Caramello" "Crunchie" "Flake" "Flake" "Crunchie"
## [6] "Crunchie" "Flake" "Dairy Milk"
count_most(a_test_pack)
## Crunchie
## 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)
## Dairy Milk Caramello Cherry Ripe
## 4 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 <- 1e6
system.time(results <- make_and_count_most(a_whole_heap))
## user system elapsed
## 150.227 0.485 150.902
table(results)
## results
## 2 3 4 5 6 7 8
## 161771 558492 227978 45578 5739 433 9
table(results[names(results)=="Cherry Ripe"])
##
## 2 3 4 5 6 7 8
## 45346 125405 45582 9146 1168 81 2